Try-Catch & Throw

Dive into 'try-catch', 'finally', and 'throw' in C#.

try-catch

The 'try-catch' block is used to handle exceptions. It allows you to catch exceptions that occur during the execution of a block of code and handle them gracefully.

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

In this structure:

The 'try' block contains the code that may throw an exception.

If an exception occurs within the 'try' block, control is transferred to the 'catch' block.

The 'catch' block catches the exception and executes the code within it to handle the exception.

finally

The 'finally' block is used to execute code regardless of whether an exception occurs or not. It's typically used for cleanup operations such as closing files or releasing resources.

try
{
    // Code that may throw an exception
}
catch (Exception ex)
{
    // Code to handle the exception
}
finally
{
    // Code that always executes
//regardless of whether an exception occurred or not
}

throw

The 'throw' keyword is used to manually throw an exception. It's often used when certain conditions are met that warrant an exceptional situation in the code.

if (condition)
{
    throw new Exception("An error occurred.");
}

If the condition evaluates to true, it will throw a new instance of the 'Exception' class with the specified error message.

Programming Example:

cs Copy Code
using System;

class Program
{
    static void Main(string[] args)
    {
        try
        {
            // This will throw an exception
            int result = Divide(10, 0); 
            // This line will not be executed
            Console.WriteLine("Result: " + result); 
        }
        catch (DivideByZeroException ex)
        {
            // Handle divide by zero exception
            Console.WriteLine("Error: " + ex.Message); 
        }
        finally
        {
            // This will be executed regardless of exception
            Console.WriteLine("Cleanup code here..."); 
        }
    }

    static int Divide(int x, int y)
    {
        if (y == 0)
            throw new DivideByZeroException("Cannot divide by zero.");
        return x / y;
    }
}

Explanation:

We attempt to divide 10 by 0, which will throw a 'DivideByZeroException'.

The catch block handles this exception and prints an error message.

The finally block ensures cleanup code is executed, regardless of whether an exception occurred or not.

Output:
Error: Cannot divide by zero.
Cleanup code here...

This is a basic overview of how 'try-catch', 'finally', and 'throw' work together in C# to handle exceptions. They are essential for writing robust and reliable code by gracefully handling unexpected situations.

What's Next?

We actively create content for our YouTube channel and consistently upload or share knowledge on the web platform.