Sobes.tech
Junior — Middle

How do you implement exception handling in your code?

sobes.tech AI

Answer from AI

In C#, exception handling is implemented using the try-catch-finally construct. The try block contains code that may throw an exception. The catch block handles specific or general exceptions. The finally block contains code that will execute in any case, such as resource cleanup.

Example:

try
{
    // Code that may throw an exception
    int result = 10 / divisor;
}
catch (DivideByZeroException ex)
{
    Console.WriteLine("Division by zero is not possible: " + ex.Message);
}
catch (Exception ex)
{
    Console.WriteLine("An error occurred: " + ex.Message);
}
finally
{
    Console.WriteLine("Processing completed.");
}

It is important to handle only those exceptions that can be properly managed, and not to use empty catch blocks without logging. Also, avoid excessive use of exceptions for controlling program logic.