C# Try-Catch
The try-catch
statement is used for exception handling. It allows you to write code that can handle potential runtime errors or exceptions gracefully, preventing your program from crashing.
Here's the basic structure of a try-catch
block.
try
{
// Code that might cause an exception
}
catch (ExceptionType1 ex1)
{
// Handle ExceptionType1
}
catch (ExceptionType2 ex2)
{
// Handle ExceptionType2
}
// ... add more catch blocks for different exception types if needed
catch (Exception ex)
{
// Handle any other exceptions
}
finally
{
// Code that will always be executed, whether an exception occurred or not
}
Here's a breakdown of the components.
try
: This block contains the code that might throw an exception.
catch
: This block is executed when a specific type of exception occurs. You can have multiple catch
blocks to handle different types of exceptions. The order of catch blocks matters; the first one that matches the exception type will be executed.
finally
: This block contains code that will always be executed, regardless of whether an exception occurred or not. It's typically used for cleanup operations.
ExceptionType
: Replace this with the specific type of exception you want to catch. For example, DivideByZeroException
, FileNotFoundException
, or a custom exception type.
Here's a simple example.
try
{
int x = 10;
int y = 0;
int result = x / y; // This will cause a DivideByZeroException
Console.WriteLine(result);
}
catch (DivideByZeroException ex)
{
Console.WriteLine("Error: Division by zero");
}
catch (Exception ex)
{
Console.WriteLine($"An unexpected error occurred: {ex.Message}");
}
finally
{
Console.WriteLine("This block always executes, whether there was an exception or not.");
}
In this example, if a DivideByZeroException
occurs, the first catch
block will handle it. If any other exception occurs, the second catch
block will handle it.
The finally
block will execute regardless of whether an exception occurred.