Junior — Middle
Kuidas toimub erandite töötlemine programmis?
sobes.tech AI
Vastus AI-lt
In C#, exception handling is done using the try-catch-finally structure.
- The
tryblock contains code that may throw an exception. - The
catchblock catches and handles exceptions of a specific type. - The
finallyblock always executes, regardless of whether an exception occurred 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: out of array bounds.");
} finally {
Console.WriteLine("Finally block executed.");
}
This way, the program will not terminate abruptly, and the exception will be handled.