Things go wrong. Files get deleted, networks fail, users enter letters where numbers belong. Exceptions are C#'s way of handling these surprises gracefully instead of crashing.
Try-Catch
Wrap risky code in a try block. If an exception happens, execution jumps to the catch block. The program keeps running instead of blowing up.
try
{
int x = int.Parse("not-a-number");
Console.WriteLine("This won't print");
}
catch (FormatException ex)
{
Console.WriteLine("Oops: " + ex.Message);
}
Console.WriteLine("Program keeps going");
Try it Yourself โ
Multiple Catch Blocks
Different exceptions need different handling. Stack multiple catch blocks โ C# tries them in order and runs the first one that matches.
try
{
string input = Console.ReadLine();
int num = int.Parse(input);
int result = 100 / num;
Console.WriteLine(result);
}
catch (DivideByZeroException)
{
Console.WriteLine("Can't divide by zero");
}
catch (FormatException)
{
Console.WriteLine("That's not a number");
}
catch (Exception ex)
{
Console.WriteLine("Something else: " + ex.Message);
}
Always put the most specific exceptions first, and Exception (the base type) last as a safety net.
Finally
The finally block runs no matter what โ whether the try succeeded or a catch ran. Use it for cleanup: closing files, releasing connections, that sort of thing.
FileStream file = null;
try
{
file = File.Open("data.txt", FileMode.Open);
}
catch (FileNotFoundException)
{
Console.WriteLine("File not found");
}
finally
{
file?.Close();
Console.WriteLine("Cleanup done");
}
Throwing Exceptions with throw
When something is wrong in your own code, throw an exception to let the caller know.
static void SetAge(int age)
{
if (age < 0)
throw new ArgumentException("Age can't be negative");
Console.WriteLine("Age set to " + age);
}
try
{
SetAge(-5);
}
catch (ArgumentException ex)
{
Console.WriteLine(ex.Message);
}
Common Exception Types
FormatExceptionโ bad format for parsingDivideByZeroExceptionโ dividing by zeroNullReferenceExceptionโ calling a method onnullIndexOutOfRangeExceptionโ accessing past array boundsFileNotFoundExceptionโ file doesn't existArgumentExceptionโ invalid argument passed