← Back to C# Course | Chapter 10: Exception Handling | Lesson 2 of 6

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:

  1. Exception Types
Syntax
csharp
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

markup
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);
        }
    }
}
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
  1. Catching the base Exception when a specific type would let you handle each case properly.
  2. Confusing ArgumentNullException with NullReferenceException.
  3. Not knowing that IndexOutOfRangeException and DivideByZeroException are runtime exceptions that you can prevent with checks.
🔒

Chapter Quiz — Complete all 6 topics to unlock

0/6 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.