Exception Types
Exception types are different kinds of problems, like a fire alarm versus a flood alarm, each named for what went wrong. Picking the right one to catch lets you respond correctly.
In this page:
Syntax
try
{
// code
}
catch (SpecificException ex) // e.g. DivideByZeroException
{
Console.WriteLine(ex.Message);
}
catch (Exception ex) // general handler last
{
}
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
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the
view already swaps in the hi_ translation fields (or blanks these
out if untranslated), so this renders correctly for both languages
without a lang_code check here. #}
Common Mistakes
- Catching the base
Exceptionwhen a specific type would let you handle each case properly. - Confusing
ArgumentNullExceptionwithNullReferenceException. - Not knowing that
IndexOutOfRangeExceptionandDivideByZeroExceptionare runtime exceptions that you can prevent with checks.
🔒
Chapter Quiz — Complete all 6 topics to unlock
0/6 topics done
Complete these topics first: