-
Notifications
You must be signed in to change notification settings - Fork 2
CSharp Exceptions TryCatch
This file will later be renamed from
Lesson01.12.2025.mdto something likeCSharp-Exceptions-TryCatch.md.
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:
- Microsoft Docs – Exceptions: https://learn.microsoft.com/dotnet/csharp/fundamentals/exceptions/
- Microsoft Docs – Exception filters: https://learn.microsoft.com/dotnet/csharp/language-reference/keywords/when
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.
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
tryblock contains code that can throw. - Each
catchblock 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).
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
whencondition must returnbool. - The condition is evaluated before the
catchblock is entered. - If the filter is
false, the runtime continues searching for another matchingcatch.
See also Microsoft Docs: https://learn.microsoft.com/dotnet/csharp/language-reference/keywords/when
- Catch specific exceptions first (
FileNotFoundException,FormatException, …), thenExceptionlast. - Avoid empty
catchblocks; 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.
- Try to provoke different exceptions (missing file, wrong input, divide by zero) and handle them.
- Read
Dependency-Injection.mdto 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).