Hiprup

How do you handle exceptions in Java? Explain the try, catch, and finally blocks.

Java handles runtime errors through exception handling: risky code is placed inside a try block, one or more catch blocks handle any exception that is thrown, and an optional finally block runs cleanup code regardless of the outcome. This stops errors like NullPointerException or ArithmeticException from abruptly terminating the program.

When an exception occurs, the JVM creates an exception object, skips the rest of the try block, and searches for the first catch whose type matches. If none matches, the exception propagates up the call stack.

  • try — wraps statements that may fail; a plain try must be followed by at least one catch or a finally (try-with-resources needs neither).

  • catch — receives the exception object; order blocks from specific to general (a catch (Exception e) placed first makes later blocks unreachable, a compile error). Java 7+ supports multi-catch: catch (IOException | SQLException e).

  • finally — always executes, even when try or catch returns; only System.exit() or a JVM crash prevents it. Ideal for releasing resources.

  • throw / throwsthrow raises an exception manually; throws declares checked exceptions a method may pass to its caller.

  • SDET usage — in Selenium frameworks, put driver.quit() in finally (or TestNG @AfterMethod) so browsers close even when a step fails, and use try-with-resources for test-data file streams.

Key terms: try, catch, finally, exception object, checked exception, unchecked exception, multi-catch, throw, throws, try-with-resources

public class ExceptionDemo {
    public static void main(String[] args) {
        try {
            int[] scores = {90, 85, 78};
            System.out.println("Score: " + scores[1]);   // Output: Score: 85
            int result = 10 / 0;                         // throws ArithmeticException
            System.out.println(result);                  // never reached
        } catch (ArrayIndexOutOfBoundsException e) {
            System.out.println("Bad index: " + e.getMessage());
        } catch (ArithmeticException e) {
            System.out.println("Math error: " + e.getMessage());
            // Output: Math error: / by zero
        } finally {
            System.out.println("finally: cleanup always runs");
            // Output: finally: cleanup always runs
        }
        System.out.println("Program continues normally");
        // Output: Program continues normally
    }
}

The division by zero throws an ArithmeticException, so the JVM skips the rest of the try block and jumps to the matching catch block, printing the error message instead of crashing. The finally block then executes, showing it runs whether or not an exception occurred, which is exactly where automation code places cleanup such as driver.quit().

Because the exception was handled, control returns to normal flow and the last print statement still runs.

Impress the interviewer by stating that finally runs even when try or catch contains a return statement, and by naming the rare cases it does not run (System.exit(), JVM crash). Expect follow-ups on final vs finally vs finalize, checked vs unchecked exceptions, and try-with-resources as the modern cleanup approach.

The classic mistake is catching Exception first, which makes more specific catch blocks unreachable and causes a compile error.