Skip to content

CSharp Exceptions TryCatch

Joe Care edited this page Dec 22, 2025 · 1 revision

C# Exceptions: try/catch and Filters

This file will later be renamed from Lesson01.12.2025.md to something like CSharp-Exceptions-TryCatch.md.

Overview

This lesson introduces the basics of exception handling in C# using try, catch, and optional exception filters (when). Correct exception handling is essential for building robust .NET applications.

Related wiki pages:

  • General C# topics: see CSharpBible.md
  • Libraries and logging: see CSharpBible-Libraries.md

Official documentation:


Why handle exceptions?

Without exception handling, any unexpected error (file missing, invalid user input, network issues, …) can terminate your program.

With try/catch you can:

  • Detect and handle predictable error situations
  • Show meaningful messages to the user
  • Log technical details for diagnostics
  • Shut down or continue in a controlled way

Do not use exceptions just to "suppress" errors. Handle only those errors that you can reasonably react to.


Basic try/catch pattern

using System;
using System.IO;

namespace MySimpleApp
{
    class Program
    {
        static void Main(string[] args)
        {
            try
            {
                // Code that may throw an exception
                string path = "data.txt";
                string content = File.ReadAllText(path);

                Console.WriteLine($"File content: {content}");
            }
            catch (FileNotFoundException ex)
            {
                // Specific handling: file not found
                Console.WriteLine($"File not found: {ex.FileName}");
                Console.WriteLine($"Details: {ex.Message}");
            }
            catch (Exception ex)
            {
                // Fallback: any other, unexpected exception
                Console.WriteLine("An unexpected error occurred.");
                Console.WriteLine(ex.Message);
            }

            Console.WriteLine("Program finished. Press any key to exit...");
            Console.ReadKey();
        }
    }
}

Key points:

  • The try block contains code that can throw.
  • Each catch block handles one exception type.
  • The last catch (Exception) is a catch-all and should be used for logging and safe shutdown.

For more console samples see CSharpBible-Library-ConsoleLib.md (if available in this wiki).


Exception filters with when

C# supports exception filters using when. These allow additional conditions on a catch block.

try
{
    Console.Write("Numerator: ");
    int numerator = int.Parse(Console.ReadLine() ?? string.Empty);

    Console.Write("Denominator: ");
    int denominator = int.Parse(Console.ReadLine() ?? string.Empty);

    int result = numerator / denominator;
    Console.WriteLine($"Result: {result}");
}
catch (DivideByZeroException ex) when (DateTime.Now.Hour < 12)
{
    // This block only runs on DivideByZeroException in the morning
    Console.WriteLine("Division by zero is not allowed (morning variant).");
    Console.WriteLine(ex.Message);
}
catch (DivideByZeroException)
{
    Console.WriteLine("Division by zero is not allowed.");
}
catch (FormatException)
{
    Console.WriteLine("Please enter valid integers only.");
}

Filter rules:

  • The when condition must return bool.
  • The condition is evaluated before the catch block is entered.
  • If the filter is false, the runtime continues searching for another matching catch.

See also Microsoft Docs: https://learn.microsoft.com/dotnet/csharp/language-reference/keywords/when


Good practices

  • Catch specific exceptions first (FileNotFoundException, FormatException, …), then Exception last.
  • Avoid empty catch blocks; always log or react.
  • Log details to a proper logging framework in real apps (see CSharpBible-Libraries.md).
  • Do not put core business logic into catch; use it only for error handling and recovery.

If you build UI apps (WPF/Avalonia), combine this with the patterns from CSharpBible-MVVM-Basics.md and the GUI topics in GUI_Window.md / Avalonia-Apps.md.


Next steps

  • Try to provoke different exceptions (missing file, wrong input, divide by zero) and handle them.
  • Read Dependency-Injection.md to see how to inject loggers and services that can help handle errors centrally.
  • Continue with LINQ basics in CSharp-LINQ-Where-Sort.md (renamed from the second lesson file).

Clone this wiki locally