C# Exceptions

In C#, exceptions are a way to handle errors or unexpected situations that occur during the execution of a program. The try, catch, and finally blocks are used to manage exceptions and provide a structured way of dealing with errors.

Try Block

The try block is used to wrap code that may potentially throw an exception. It contains the code that might result in an error during execution.

Syntax:


try
{
    // Code that may throw an exception
}

Example: Divide number by zero


try
{
    int result = 50 / 0;  // This will throw a DivideByZeroException
    Console.WriteLine(result);
}

Catch Block

The catch block follows the try block and handles any exceptions thrown in the try block. It catches specific exceptions or a generic exception. Multiple catch blocks can be used to handle different types of exceptions.

Syntax:


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

Example: Divide number by zero then through exception


try
{
    int result = 50 / 0;  // This will throw a DivideByZeroException
    Console.WriteLine(result);
}
catch (DivideByZeroException ex)
{
    Console.WriteLine("We can not divide by zero.");
}

Finally Block

The finally block in C# is used to define code that will always be executed, regardless of whether an exception was thrown or not. It is typically used for cleanup operations, such as releasing resources, closing files, or closing database connections, ensuring that these actions happen even if an error occurs.

Syntax:


try
{
    // Code that may throw an exception
}
catch (Exception ex)
{
    // Handle the exception
}
finally
{
    // Code that will always execute
}

Complete Example of Exception:


using System;

class MyProgram
{
    static void Main()
    {
        try
        {
            int result = 50 / 0;
        }
        catch (DivideByZeroException ex)
        {
            Console.WriteLine("Error: Cannot divide by zero.");
        }
        // Finally Block (Always Executes)
        finally
        {
            Console.WriteLine("This will execute always.");
        }
    }
}