Lesson 41 +10 XP

C# Exceptions

C# Exceptions

When C# code hits an error at runtime, it throws an exception. If nothing catches it, the program stops. try...catch lets you handle errors gracefully.

try and catch

try
{
  int[] myNumbers = { 1, 2, 3 };
  Console.WriteLine(myNumbers[10]);   // index out of range!
}
catch (Exception e)
{
  Console.WriteLine("Something went wrong.");
}

The catch block runs when the try block throws. The program keeps going instead of crashing.

Multiple catch blocks

You can catch specific exception types:

try
{
  ...
}
catch (IndexOutOfRangeException e)
{
  Console.WriteLine("Index is out of range.");
}
catch (Exception e)
{
  Console.WriteLine("Something else went wrong.");
}

Put specific exceptions first, and the general Exception last.

finally

The finally block always runs - whether or not an exception happened:

try
{
  ...
}
catch (Exception e)
{
  ...
}
finally
{
  Console.WriteLine("The 'try catch' is finished.");
}

Perfect for cleanup like closing files or releasing resources.

throw

You can throw your own exceptions:

if (age < 18)
{
  throw new ArithmeticException("Access denied - you must be at least 18.");
}

Common exception types

  • IndexOutOfRangeException - array index out of bounds.
  • FormatException - bad string-to-number conversion.
  • NullReferenceException - calling a member on null.
  • DivideByZeroException - dividing by zero.

TL;DR

  • try wraps risky code; catch handles errors.
  • finally always runs (great for cleanup).
  • throw raises your own exception.
  • Catch specific exceptions before the general Exception.