Try & Catch

Lesson 24
Author : Afrixi
Last Updated : February, 2023


C# - Programming Language
This course covers the basics of programming in C#.

In C#, try-catch is a feature used to handle exceptions. An exception is an unexpected error that occurs while the program is running. By using a try-catch block, we can catch these exceptions and handle them gracefully, preventing the program from crashing.

Here’s the basic syntax for a try-catch block in C#:


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

The try block contains the code that might throw an exception. If an exception is thrown, the catch block catches the exception and handles it. The ExceptionType parameter in the catch block specifies the type of exception that is caught.

Here’s an example of a try-catch block in action:

int num1 = 10;
int num2 = 0;

try
{
    int result = num1 / num2;
    Console.WriteLine(result);
}
catch (DivideByZeroException ex)
{
    Console.WriteLine("Error: Attempted to divide by zero.");
}

In this example, we’re attempting to divide num1 by num2, which is zero. This will result in a DivideByZeroException. We’ve wrapped this code in a try block and caught the exception in a catch block. We’ve specified that we want to catch DivideByZeroException using the catch (DivideByZeroException ex) statement. If an exception is caught, the catch block will execute and output an error message.

Using try-catch blocks is a good practice to handle errors and prevent the program from crashing due to unexpected exceptions. It’s important to handle exceptions properly to ensure the stability and reliability of the program.