csharp-bloque-try-catch

The Try-Catch Block in C#

  • 3 min

The try-catch block in C# is used to catch and handle exceptions (errors) that may occur during program execution.

An exception is an unexpected event that interrupts the normal flow of the program. The goal of the try-catch block is to allow the program to respond to these events in a controlled manner, instead of terminating abruptly.

Basic Structure

The basic structure of the try-catch block is as follows:

try
{
    // Code that may throw an exception
}
catch (Exception exceptionType)
{
    // Code to handle the exception
}
Copied!

In this structure,

  • The try block contains the code you want to monitor for potential exceptions.
  • The catch block contains the code that will execute if an exception occurs.

Basic Example

Consider an example where we try to divide two numbers and handle a possible division by zero:

try
{
    int divisor = 0;
    int result = 10 / divisor;
}
catch (DivideByZeroException ex)
{
    Console.WriteLine("Error: Division by zero is not allowed.");
    Console.WriteLine($"Details: {ex.Message}");
}
Copied!

In this example, the try block attempts to divide 10 by 0, which causes a DivideByZeroException. The catch block catches this exception and provides an informative error message.

Catching Multiple Exceptions

You can have multiple catch blocks to handle different types of exceptions specifically:

try
{
    // Code that may throw exceptions
}
catch (DivideByZeroException ex)
{
    Console.WriteLine("Error: Division by zero.");
}
catch (NullReferenceException ex)
{
    Console.WriteLine("Error: Null reference.");
}
catch (Exception ex)
{
    Console.WriteLine("Error: A general error occurred.");
}
Copied!

In this example, DivideByZeroException, NullReferenceException, and a generic Exception are handled, which catches any other type of exception not specifically handled.

Using the finally Block

The finally block can be used to execute code that must run regardless of whether an exception occurred or not. It is useful for releasing resources, closing files, or performing other cleanup tasks.

try
{
    // Code that may throw an exception
}
catch (Exception ex)
{
    Console.WriteLine($"Error: {ex.Message}");
}
finally
{
    Console.WriteLine("This block always executes.");
}
Copied!

In this example, the finally block will always execute, whether an exception was thrown or not.

Practical Examples