Junior — Middle
Can you explain what the try operator means in programming and how it is used for error handling?
sobes.tech AI
Answer from AI
The try operator in C# is used for exception handling — errors that may occur during program execution. Code that potentially can cause an error is placed inside a try block. If an exception occurs in this block, control is transferred to the corresponding catch block, where the error can be handled, for example, by displaying a message or performing alternative actions.
Example of usage:
try
{
int[] numbers = {1, 2, 3};
Console.WriteLine(numbers[5]); // Attempt to access a non-existent element
}
catch (IndexOutOfRangeException ex)
{
Console.WriteLine("Error: array index out of bounds.");
}
You can also use a finally block, which executes always, regardless of whether an exception occurred or not, for example, to release resources.