Skip to content
dreamcode
dreamcode
Map
Exception handling
Lesson 11 of 21
+15 XP on finish
C# INTERMEDIATEChapter 4 · C# Intermediate

Exception handling

C# uses try-catch-finally blocks to handle exceptions. The finally block executes whether an exception occurs or not, which is ideal for cleaning up resources.

Worked example
try {
    int x = 0;
    int y = 10 / x;
} catch (DivideByZeroException ex) {
    Console.WriteLine("Math error: " + ex.Message);
} finally {
    Console.WriteLine("Execution complete.");
}

How it reads

  • try blocks hold code that could throw an exception
  • catch (DivideByZeroException) handles specific division by zero arithmetic errors
  • finally always runs at the end of the error handling sequence
Cloud tip: Always list more specific catch blocks (e.g. DivideByZeroException) before a general catch-all Exception block.

Check your understanding

0 / 2

Answer all 2 to complete this lesson and earn 15 XP.

  1. 1. Which block in exception handling runs regardless of whether an error was thrown?
  2. 2. What base class do all built-in C# exceptions derive from?
Answer every question to unlock the next lesson.