C#
try/catch
Learn to catch runtime errors with try/catch.
Catching errors with try/catch
In C#, when a runtime error (exception) occurs, the program normally crashes. To prevent this, you put risky code in a try block and error-handling code in a catch block. When an exception is thrown, the catch block runs and the program continues.
For example, in try { int n = int.Parse("abc"); } catch (Exception) { ... }, int.Parse throws a FormatException; the catch block catches it and the program continues without crashing.
Multiple catch blocks
You can write multiple catch blocks after a single try block. Each catches a different exception type. More specific types come first, more general ones later, because the first matching catch runs.
For example, in catch (FormatException) { ... } catch (Exception) { ... }, format errors are caught first, then general exceptions. Exception is the most general type and must always come last; otherwise the other catches are unreachable.
Specific exception types
C# provides many built-in exception types. FormatException is thrown for bad string conversions, DivideByZeroException for division by zero, and IndexOutOfRangeException for array bound violations. Catching by type lets you respond to the specific error.
For example, catch (DivideByZeroException) only catches division-by-zero errors; other exceptions skip this block. This lets you give different messages or recovery strategies for different error types.
Exercise Catch division by zero
Inside a try block, divide with int c = a / b;. Since b is zero, a DivideByZeroException will be thrown. In a catch (DivideByZeroException) block, print "Division by zero error" with Console.WriteLine.
Show example solution
Write try { int c = a / b; } then add catch (DivideByZeroException) { Console.WriteLine("Division by zero error"); }
Example solution:
using System;
class Program
{
static void Main()
{
int a = 10;
int b = 0;
try
{
int c = a / b;
}
catch (DivideByZeroException)
{
Console.WriteLine("Division by zero error");
}
}
}
Test yourself
-
What happens when an exception is thrown in the try block?
try { int n = int.Parse("abc"); }
catch (Exception) { Console.WriteLine("Error"); }
- The program crashes
- The catch block runs
- The try block continues
- FormatException is thrown and the program stops
Show answer
The catch block runs — Correct! When an exception is thrown, the try block is interrupted and catch runs.
-
catch syntax
try { int n = int.Parse("abc"); }
____ { Console.WriteLine("Error"); }
Show answer
try { int n = int.Parse("abc"); }
catch (Exception) { Console.WriteLine("Error"); }
-
Match each exception with its scenario
- FormatException
- Invalid string
- DivideByZeroException
- Division by zero
- IndexOutOfRangeException
- Array bounds
Next lesson: finally block