Exception Handling — try/catch/finally

লেসন ৮ / ৫০

try / catch / finally

try {
    string content = File.ReadAllText("data.txt");
    int n = int.Parse(content);
}
catch (FileNotFoundException ex) {
    Console.WriteLine($"File নেই: {ex.Message}");
}
catch (FormatException ex) {
    Console.WriteLine($"Format ভুল: {ex.Message}");
}
catch (Exception ex) {        // generic — সবার শেষে
    Console.WriteLine($"Error: {ex.Message}");
    Console.WriteLine(ex.StackTrace);
}
finally {
    // সবসময় চলবে — cleanup
    Console.WriteLine("Done");
}

Exception Filter (C# 6+)

try {
    // ...
}
catch (HttpRequestException ex) when (ex.StatusCode == 404) {
    Console.WriteLine("Not Found");
}
catch (HttpRequestException ex) when (ex.StatusCode >= 500) {
    Console.WriteLine("Server error");
}

throw ও re-throw

public int Divide(int a, int b) {
    if (b == 0)
        throw new DivideByZeroException("Cannot divide by zero");
    return a / b;
}

try {
    Divide(10, 0);
}
catch (Exception ex) {
    Log(ex);
    throw;        // re-throw, stack trace preserve
    // throw ex; — stack trace লস হবে (avoid)
}

Custom Exception

public class InsufficientBalanceException : Exception {
    public decimal Balance { get; }
    public decimal Requested { get; }

    public InsufficientBalanceException(decimal balance, decimal requested)
        : base($"Balance {balance}, requested {requested}") {
        Balance = balance;
        Requested = requested;
    }
}

// ব্যবহার
if (account.Balance < amount)
    throw new InsufficientBalanceException(account.Balance, amount);

using — Resource Cleanup

// Old style
using (var stream = new FileStream("a.txt", FileMode.Open)) {
    // use stream
}   // auto Dispose()

// C# 8+ using declaration
using var stream = new FileStream("a.txt", FileMode.Open);
// scope শেষে auto Dispose

Common Exception Types

  • ArgumentNullException
  • ArgumentException / ArgumentOutOfRangeException
  • InvalidOperationException
  • NotImplementedException / NotSupportedException
  • NullReferenceException
  • IOException, FileNotFoundException