Junior — Middle
Explain the purpose of the try-catch construct and how it works when handling exceptions in a program.
sobes.tech AI
Answer from AI
The try-catch construct in Java is used for exception handling — errors that may occur during program execution.
- The code that might throw an exception is placed inside the
tryblock. - If an exception occurs, execution is interrupted, and control is transferred to the corresponding
catchblock, where the error can be handled (e.g., display a message, log it, perform alternative actions).
This allows the program not to terminate abruptly on errors but to react to them properly.
Example:
try {
int result = 10 / 0; // will throw ArithmeticException
} catch (ArithmeticException e) {
System.out.println("Division by zero is not possible: " + e.getMessage());
}
In this example, the division by zero exception is caught and handled, preventing the program from crashing.