Junior — Middle
Can you explain the principle of the try-catch construct in programming and what it is used for?
sobes.tech AI
Answer from AI
The try-catch construct in programming is used for exception handling — unexpected errors that may occur during program execution.
Principle of operation:
- Code that might cause an error is placed inside a
tryblock. - If an exception occurs in the
tryblock, execution is interrupted and control is transferred to the correspondingcatchblock, where the error can be handled (for example, by displaying a message, logging, or performing alternative actions). - If no exception occurs, the
catchblock is skipped.
This allows the program not to crash on errors, but to handle them properly and continue working or terminate correctly.
Example in C#:
try
{
int result = 10 / divisor; // may cause division by zero
Console.WriteLine(result);
}
catch (DivideByZeroException ex)
{
Console.WriteLine("Error: division by zero.");
}
In this example, if divisor is zero, the program will not crash but will display an error message.