Sobes.tech
Junior — Middle

How is exception handling implemented in the program?

sobes.tech AI

Answer from AI

In C#, exception handling is performed using the try-catch-finally construct.

  • The try block contains code that may throw an exception.
  • The catch block catches and handles exceptions of a specific type.
  • The finally block always executes, regardless of whether an exception was thrown or not, and is usually used for resource cleanup.

Example:

try {
    int[] numbers = {1, 2, 3};
    Console.WriteLine(numbers[5]); // will throw IndexOutOfRangeException
} catch (IndexOutOfRangeException ex) {
    Console.WriteLine("Error: array index out of bounds.");
} finally {
    Console.WriteLine("Finally block executed.");
}

Thus, the program will not terminate abruptly, and the exception will be handled.