C# Keywords Tutorial Part 13: catch

C# Keywords Tutorial Part 13: catch

C# is a modern, object-oriented programming language that is widely used to develop a wide range of applications. One of the key features of C# is its robust error handling mechanism, which allows developers to write code that can handle errors gracefully.

The “catch” keyword is an essential part of C#’s error handling mechanism. It allows developers to catch exceptions that are thrown by their code, and take appropriate actions to handle them.

Syntax of the “catch” keyword:

try
{
    //Code block that might throw an exception
}
catch(ExceptionType1 ex1)
{
    //Code block to handle ExceptionType1
}
catch(ExceptionType2 ex2)
{
    //Code block to handle ExceptionType2
}
finally
{
    //Code block that will always execute
}

Here’s an example of how the “catch” keyword works in C#. In this example, we are dividing two numbers, and catching any exceptions that might be thrown if the second number is zero.

static void Main(string[] args)
{
    int num1 = 10;
    int num2 = 0;
    try
    {
        int result = num1 / num2;
        Console.WriteLine("Result: " + result);
    }
    catch(DivideByZeroException ex)
    {
        Console.WriteLine("Error: " + ex.Message);
    }
    finally
    {
        Console.WriteLine("Finally block executed.");
    }
}

In the code above, we are attempting to divide the integer “num1” by the integer “num2”. Since “num2” is zero, this will cause a “DivideByZeroException” to be thrown. We catch this exception using the “catch” keyword, and print out an error message to the console.

The “finally” block is optional, but it will always execute regardless of whether an exception is thrown or not. In this case, we are using the “finally” block to print a message to the console indicating that the block has executed.

Share this post

Leave a Reply

Your email address will not be published. Required fields are marked *