C#•Error Handling
C# Exception Handling: try, catch, finally, and Exception Filters
Learn structured exception handling in C# and conditional exception filters using the when keyword.
Syntax
try {
// code
} catch (Exception ex) when (ex.HResult == 5) {
// filtered
}
Parameters & Values
Key components and acceptable values for this structure:
| Parameter | Type | Description |
|---|---|---|
| when | Exception Filter | Executes catch block only if boolean condition is met. |
Ready-to-Run Code Example
Executable in CompilraRun this complete, working example directly without installing C# locally:
using System;
public class Program {
public static double Divide(double numerator, double denominator) {
if (denominator == 0) {
throw new DivideByZeroException("Denominator cannot be zero in calculation.");
}
return numerator / denominator;
}
public static void Main() {
try {
Console.WriteLine("100 / 4 = " + Divide(100, 4));
Console.WriteLine("50 / 0 = " + Divide(50, 0));
} catch (DivideByZeroException ex) {
Console.WriteLine($"[CAUGHT] Math Error: {ex.Message}");
} finally {
Console.WriteLine("[CLEANUP] Routine complete.");
}
}
}Expected Output:
100 / 4 = 25 [CAUGHT] Math Error: Denominator cannot be zero in calculation. [CLEANUP] Routine complete.
How It Works: Step-by-Step
- Lines 4-9: Throws DivideByZeroException when denominator is zero.
- Lines 12-19: try-catch catches specific exception and runs finally block.
Key Concepts
- Catch specific exceptions instead of generic catch(Exception) to avoid masking unexpected bugs.
- finally blocks execute unconditionally even when return statements are present.
Common Mistake: Rethrowing exceptions with throw ex instead of throw
Writing throw ex resets the stack trace to the current line, destroying debugging history. Use throw;.
❌ Incorrect
catch (Exception ex) { throw ex; // Stack trace destroyed! }✅ Correct
catch (Exception ex) { throw; // Preserves original stack trace }Related C# Tutorials & Compiler
C# Async/Await and Task Concurrency (Task.WhenAll)
Master asynchronous programming in C# with async, await, Task, and Task.WhenAll.
C# Classes, Records, and Properties (get; set;)
Design objects using classes, auto-properties ({ get; set; }), and modern C# records.
C# Named and Optional Parameters in Method Definitions
Define flexible C# methods using optional parameters with defaults and named arguments (name: value) for order independence and clarity.
C# Online Compiler
Open in Compilra IDE
Run and test C# on Compilra
Execute this code snippet with pre-supplied standard input (stdin) in Compilra’s cloud compiler.