Mastering Exception Handling in C# with `try-catch` Blocks
Learn how to effectively handle exceptions in C# using `try-catch` statements. This tutorial provides a comprehensive guide to exception handling, including handling specific exception types, using multiple `catch` blocks, and preventing program crashes due to unhandled errors.
Exception Handling in C# Using `try-catch`
In C#, the `try-catch` statement is the fundamental mechanism for handling exceptions (runtime errors). It helps prevent your program from crashing due to unexpected errors and allows you to gracefully manage and respond to these issues.
The `try` Block
The `try` block encloses the code that might throw an exception. If an exception occurs within the `try` block, the program's execution jumps to the associated `catch` block.
The `catch` Block
The `catch` block handles exceptions. You can specify the type of exception you want to catch. If an exception of that type occurs in the `try` block, the code within the `catch` block is executed. A `catch` block must be placed after a `try` block. You can have multiple `catch` blocks to handle different exception types.
Example: Handling `DivideByZeroException`
This example demonstrates basic exception handling. The `try` block attempts a division by zero, which throws a `DivideByZeroException`. The `catch` block catches this exception and prints an error message. Note that the "Rest of the code" line is executed even though an exception occurred.
try {
int result = 10 / 0; // This will throw a DivideByZeroException
} catch (DivideByZeroException ex) {
Console.WriteLine($"Error: {ex.Message}");
}
Console.WriteLine("Rest of the code");
Example: Without `try-catch`
If you don't handle the exception, the program will terminate with an unhandled exception message.
int a = 10;
int b = 0;
int x = a / b; //Unhandled exception will occur here.
Console.WriteLine("This line won't execute.");