Sobes.tech
Junior — Middle

How can a situation be handled when an exception occurs in a program?

sobes.tech AI

Answer from AI

In Java, exception handling is done using the try-catch-finally construct. The try block contains code that might throw an exception. If an exception occurs, control is transferred to the corresponding catch block, where the error can be handled or alternative actions can be taken. The finally block is always executed, regardless of whether an exception was thrown, and is usually used for resource cleanup.

Example:

try {
    int result = 10 / 0; // will throw ArithmeticException
} catch (ArithmeticException e) {
    System.out.println("Division by zero is not possible: " + e.getMessage());
} finally {
    System.out.println("Finally block executed");
}