How to implement Exception Handling in C#?

Exception handling in Object-Oriented Programming is used to MANAGE ERRORS.

  • TRY − A try block is a block of code inside which any error can occur.
  • CATCH − When any error occur in TRY block then it is passed to catch block to handle it.
  • FINALLY − The finally block is used to execute a given set of statements, whether an exception occur or not.

Here's the general structure of exception handling in C#:

try
{
    // Code that may throw an exception
}
catch (ExceptionType1 ex1)
{
    // Exception handling specific to ExceptionType1
}
catch (ExceptionType2 ex2)
{
    // Exception handling specific to ExceptionType2
}
finally
{
    // Code that always executes, regardless of whether an exception is thrown or not
}

It's important to note that the catch blocks are optional, but at least one of them or a finally block must be present. Additionally, the catch blocks are evaluated in the order they appear, so it's important to consider the order when handling multiple exception types.

Example:

try
{
    // Code that may throw an exception
    int result = 10 / 0;  // Division by zero exception
}
catch (DivideByZeroException ex)
{
    Console.WriteLine("Divide by zero error: " + ex.Message);
}
catch (Exception ex)
{
    Console.WriteLine("An error occurred: " + ex.Message);
}
finally
{
    Console.WriteLine("Finally block executed.");
} 

In the above example, the try block attempts to perform a division by zero operation, which throws a DivideByZeroException. The first catch block specifically handles this exception and displays a corresponding message. If any other exception occurs, the second catch block handles it and provides a generic error message. Finally, the finally block executes regardless of whether an exception occurred or not.

By using exception handling, you can gracefully handle and recover from exceptions, perform necessary cleanup, and ensure the stability and robustness of your application.

Post a Comment

Previous Post Next Post