Interview Q&A · Java · 10 questions in this topic

try, catch, finally and Multi-Catch — Java Interview Q&A

All Java topics

How guarded blocks, handlers, cleanup sections, and combined catch clauses work together to manage failures safely. Part of Exception Handling · 294 questions in the Java bank.

Explain the try and catch keywords.

Answer

The try block encloses code that might throw, and each catch block attached to it handles one failure type for that try only. When an exception occurs, the JVM skips the rest of the try and jumps to the first matching catch. Since Java 7, a try-with-resources statement can also declare closable resources that are shut down automatically.

Example

Example.javajava
try {
    int x = Integer.parseInt("abc");
} catch (NumberFormatException e) {
    System.out.println("Not a number: " + e.getMessage());
}

Can a try block exist without catch?

Answer

Yes, a try block can exist without a catch as long as it has either a finally block or a resource specification. A try-finally construct is useful when cleanup is needed but the method does not want to handle the exception itself. A bare try with neither catch, finally, nor resources is a compile error.

Example

Example.javajava
try {
    System.out.println("Using a resource");
} finally {
    System.out.println("Cleanup always runs");
}

Can there be multiple catch blocks for one try?

Answer

Yes, one try can have several catch blocks when different failures need different responses. When an exception is thrown, the JVM checks the catch clauses in order and runs the first one whose type matches, skipping the rest. The order must run from child to parent types, because placing a parent first makes the child catch unreachable and causes a compile error.

Example

Example.javajava
try {
    int[] a = new int[3];
    int x = a[10];
} catch (ArrayIndexOutOfBoundsException e) {
    System.out.println("Bad index");
} catch (RuntimeException e) {
    System.out.println("Other runtime failure");
}

Recommended resourcesAffiliate links · may earn us a commission

Classic DSA interview booksThe reference books interviewers themselves learned from — great next to the visualizers.See the books Structured coding coursesVideo courses that pair well with visual practice — pick one language and go deep.Browse courses Cloud hosting for side projectsShip the portfolio project that gets you hired — free credits for new accounts.Claim credits