Sobes.tech
Junior — Middle

How to implement handling of various exceptional situations in a program?

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 catches and handles exceptions of a specific type.
  • The finally block always executes, regardless of whether an exception was thrown, and is usually used for resource cleanup.

Example:

try
{
    int result = 10 / divisor; // may throw DivideByZeroException
    Console.WriteLine(result);
}
catch (DivideByZeroException ex)
{
    Console.WriteLine("Error: division by zero.");
}
catch (Exception ex)
{
    Console.WriteLine($"An error occurred: {ex.Message}");
}
finally
{
    Console.WriteLine("Operation completed.");
}

You can also create custom exception classes inheriting from Exception to handle specific errors more precisely.