Light Mode Image

C# Exception Handling

Exception handling is a mechanism that allows you to gracefully handle runtime errors or exceptional situations that may occur during the execution of a program. Exceptions are events that occur during the execution of a program that disrupt the normal flow of instructions.

 

Here's a basic overview of exception handling in C#.

 

Try-Catch Blocks

 

The basic structure for handling exceptions in C# is the try-catch block. The code that might throw an exception is placed within the try block, and the code that handles the exception is placed within the catch block.

try
{
    // Code that may throw an exception
}
catch (ExceptionType ex)
{
    // Code to handle the exception
}

 

The catch block is executed only if an exception of the specified type occurs within the try block.

 

Multiple Catch Blocks

 

You can have multiple catch blocks to handle different types of exceptions. They are evaluated in order, and the first one that matches the exception type is executed.

try
{
    // Code that may throw an exception
}
catch (DivideByZeroException ex)
{
    // Code to handle DivideByZeroException
}
catch (Exception ex)
{
    // Code to handle other exceptions
}

 

Finally Block

 

The finally block is used to specify a block of code that is always executed, regardless of whether an exception occurred or not. It is typically used for cleanup operations.

try
{
    // Code that may throw an exception
}
catch (Exception ex)
{
    // Code to handle the exception
}
finally
{
    // Code that always executes, e.g., cleanup code
}

 

Throw Statement

 

You can use the throw statement to manually throw an exception. This is useful when you want to create custom exceptions or rethrow exceptions.

if (someCondition)
{
    throw new CustomException("This is a custom exception.");
}

 

Custom Exceptions

 

You can create your own exception classes by deriving from the Exception class or one of its subclasses.

public class CustomException : Exception
{
    public CustomException(string message) : base(message)
    {
    }
}

 

Exception Filters (C# 6 and later)

 

You can use exception filters to specify conditions that must be met for a catch block to be executed.

try
{
    // Code that may throw an exception
}
catch (Exception ex) when (ex.Message.Contains("specific condition"))
{
    // Code to handle the exception with a specific condition
}

 

It's generally a good practice to catch only the exceptions you expect and can handle, and allow others to propagate up the call stack. This helps in maintaining a clean and understandable codebase.