Sobes.tech
Junior — Middle

How do you use the try construct for exception handling in your projects?

sobes.tech AI

Answer from AI

In C#, the try construct is used for exception handling, allowing the program to continue running or terminate gracefully when errors occur. The try block contains code that might throw an exception, and the catch block handles that exception.

Example of usage:

try
{
    int result = 10 / divisor; // divisor can be 0
    Console.WriteLine($"Result: {result}");
}
catch (DivideByZeroException ex)
{
    Console.WriteLine("Error: division by zero.");
}
finally
{
    Console.WriteLine("The finally block always executes.");
}

This approach helps avoid abrupt program termination and allows logging or proper response to errors.