Exception Handling: try, catch, finally and Custom Exceptions

Dot NET Programming 15 min min read Updated: Nov 16, 2026 Intermediate
Exception Handling: try, catch, finally and Custom Exceptions
Intermediate Topic 8 of 9

What is an Exception?

An exception is an error that happens while the program runs, such as dividing by zero or opening a missing file. If you do nothing, the program crashes. With exception handling you decide what happens next.

try and catch

csharp try { Console.Write("Enter a number: "); int n = int.Parse(Console.ReadLine()!); Console.WriteLine(100 / n); } catch (FormatException) { Console.WriteLine("That is not a number."); } catch (DivideByZeroException) { Console.WriteLine("You cannot divide by zero."); } catch (Exception ex) { Console.WriteLine($"Unexpected error: {ex.Message}"); }
Order matters: Put the specific exceptions first and the general Exception last. C# uses the first matching catch.

finally: Always Runs

csharp StreamReader? reader = null; try { reader = new StreamReader("data.txt"); Console.WriteLine(reader.ReadLine()); } catch (FileNotFoundException) { Console.WriteLine("File not found."); } finally { reader?.Dispose(); // runs whether or not an error happened }

using: The Easier Way to Clean Up

csharp try { using var reader = new StreamReader("data.txt"); Console.WriteLine(reader.ReadLine()); } // reader is closed automatically here, even if an exception is thrown catch (FileNotFoundException) { Console.WriteLine("File not found."); }

Throwing Exceptions

csharp void Withdraw(decimal balance, decimal amount) { ArgumentOutOfRangeException.ThrowIfNegativeOrZero(amount); if (amount > balance) throw new InvalidOperationException("Not enough money."); }

Rethrow Correctly

csharp try { Process(); } catch (Exception ex) { Console.WriteLine($"Logging: {ex.Message}"); throw; // keeps the original stack trace // throw ex; // BAD: resets the stack trace }

Custom Exceptions

csharp public class InsufficientFundsException : Exception { public decimal Missing { get; } public InsufficientFundsException(decimal missing) : base($"You need {missing:C} more.") { Missing = missing; } } // usage // throw new InsufficientFundsException(25m);

Exception Filters

csharp try { /* ... */ } catch (HttpRequestException ex) when (ex.StatusCode == System.Net.HttpStatusCode.NotFound) { Console.WriteLine("Resource does not exist."); }

Best Practices

  • Catch only what you can handle. Do not hide errors with an empty catch.
  • Use TryParse and if checks for expected problems. Exceptions are for the unexpected.
  • Always release resources with using.
  • Log the exception, then rethrow with throw; if you cannot fix it.
  • Include useful messages for the person who reads the log.
Performance: Throwing exceptions is slow compared with normal code. Do not use them for ordinary flow control in loops.

Conclusion

Wrap risky code in try, catch specific exceptions, clean up with using or finally and throw meaningful exceptions of your own when your rules are broken.

Quick Summary: try, catch specific first, finally or using for cleanup, throw; to rethrow.

Get Newsletter

Subscibe to our newsletter and we will notify you about the newest updates on Edugators