Exceptions

View saved

Try and catch

Wrap risky work and handle known exception types.

try
{
    int n = int.Parse("abc");
    Console.WriteLine(n);
}
catch (FormatException ex)
{
    Console.WriteLine($"Bad number: {ex.Message}");
}

Throw when invalid

Raise an exception when the caller broke a contract.

void SetAge(int age)
{
    if (age < 0)
        throw new ArgumentOutOfRangeException(nameof(age));
}

Finally for cleanup

finally runs whether or not an exception occurred.

StreamReader? reader = null;
try
{
    reader = File.OpenText("notes.txt");
    Console.WriteLine(reader.ReadLine());
}
finally
{
    reader?.Dispose();
}

Exception tips

  • Catch specific exceptions before broader ones
  • Do not use exceptions for ordinary control flow
  • Include useful messages
  • Prefer using statements for disposable resources

Comments

One comment per signed-in account. Comments are saved with this page’s URL.