Sobes.tech
Junior — Middle

How is error handling and exceptional situations managed in the code?

sobes.tech AI

Answer from AI

In C#, error handling and exceptional situations are managed using the try-catch-finally construct.

  • The try block contains code that may throw an exception.
  • The catch block handles exceptions of a specific type.
  • The finally block always executes, regardless of whether an exception was thrown or not, and is typically 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.");
}

You can also use multiple catch blocks to handle different exception types.

Additionally, in C#, you can create custom exception classes by inheriting from Exception.