Exception Types
In this page:
Exception Types
C# has a hierarchy of built-in exception types like ArgumentException, NullReferenceException, and DivideByZeroException, all deriving from System.Exception. Catching a more specific type first lets you handle different failures differently. A catch-all catch (Exception ex) should generally come last.
Note: Order catch blocks from most specific to most general — the compiler enforces this for related types.
Example: Exception Types
using System;
class Program
{
static void Main(string[] args)
{
try
{
int a = 10;
int b = 0;
Console.WriteLine(a / b);
}
catch (DivideByZeroException ex)
{
Console.WriteLine("Division error: " + ex.Message);
}
catch (Exception ex)
{
Console.WriteLine("General error: " + ex.Message);
}
}
}
Login to try C/C++/Java/PHP code in the editor
🔒
Chapter Quiz — Complete all 6 topics to unlock
0/6 topics done
Complete these topics first: