Exception Handling Best Practices

Intermediate Updated March 21, 2025

🧩 Exception Handling Best Practices

🔸 Creating Custom Exceptions

class InvalidGradeException : Exception
{
    public InvalidGradeException(string message) : base(message) {}
}

void SetGrade(int grade)
{
    if (grade < 0 || grade > 100)
        throw new InvalidGradeException("Grade must be between 0 and 100.");
}

### 🔸 `try-catch-finally` Block

```csharp
try
{
    var data = File.ReadAllText("config.txt");
}
catch (FileNotFoundException ex)
{
    Console.WriteLine("File not found.");
}
finally
{
    Console.WriteLine("Always executes.");
}