C#:C# Exception Handling: try, catch, finally, and Exception Filters
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:

ParameterTypeDescription
whenException FilterExecutes catch block only if boolean condition is met.

Ready-to-Run Code Example

Executable in Compilra

Run 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

Run and test C# on Compilra

Execute this code snippet with pre-supplied standard input (stdin) in Compilra’s cloud compiler.

C# Online Compiler