Interview Q&A · Java · 10 questions in this topic
try, catch, finally and Multi-Catch — Java Interview Q&A
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
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
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
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"); }
Why is the finally block important?
Answer
The finally block holds cleanup code that must run whether the try succeeds, fails with a caught exception, or fails with an uncaught one. It is the natural place to close files, sockets, and locks or to release other held resources. Modern code often uses try-with-resources for closable resources, but finally is still needed for non-closable cleanup.
Example
java.io.BufferedReader br = null; try { br = new java.io.BufferedReader(new java.io.FileReader("data.txt")); System.out.println(br.readLine()); } catch (java.io.IOException e) { System.out.println("Read failed"); } finally { if (br != null) { try { br.close(); } catch (java.io.IOException ignored) {} } }
Can code appear between try and catch?
Answer
No, no statements may appear between the end of a try block and its catch clauses. The catch must follow the try directly, and anything placed in between causes a compile error. Comments and whitespace are fine, but executable statements are not allowed there.
Can code appear between try/catch and finally?
Answer
No, the same direct-attachment rule applies to finally. A finally block must immediately follow the try block or the last catch block, with no statements in between. Any code placed there produces a compile error, so shared logic should go inside the finally block itself.
Can one catch block handle multiple exception types?
Answer
Yes, since Java 7 a single catch can handle several unrelated types with a multi-catch clause that separates the types with a single vertical bar. The caught parameter is implicitly final, so it cannot be reassigned inside the block. Note that source text showing a double bar is wrong, since logical OR syntax is not allowed in a catch clause.
Example
try { readConfig(); } catch (java.io.IOException | java.sql.SQLException e) { System.out.println("Config load failed: " + e.getMessage()); }
💡 Multi-catch works only for unrelated types; listing a child and its parent together is a compile error.
How do finally and return interact?
Answer
If a try or catch block contains a return, the finally block still runs before the method actually returns. The pending return value is held while finally executes, and only then does control leave the method. A return or throw inside finally overrides any earlier return or exception, which is confusing, so it should be avoided.
💡 Never place return, break, or throw inside finally; use it only for cleanup.
When does finally NOT execute?
Answer
In normal execution finally almost always runs, including after returns, breaks, and uncaught exceptions. The main exceptions are abrupt JVM termination such as System.exit, a JVM crash, power loss, or an infinite loop that never lets control leave the try. Daemon threads abandoned during JVM shutdown may also not run their finally blocks. Apart from those cases, assume finally will execute.
Key points
- 1System.exit stops the JVM before finally can run.
- 2JVM crash, power loss, or forced kill prevents further execution.
- 3An infinite loop or deadlock inside try delays finally indefinitely.
- 4Daemon threads may be abandoned when the JVM shuts down.
Can try blocks be nested?
Answer
Yes, try blocks can be nested, with one try-catch-finally structure placed inside another try or catch block. An exception is first offered to the inner handlers, and only if none matches does it propagate to the outer handler. This layering lets inner code handle specific failures while outer code acts as a fallback for the rest.
Example
try { try { int x = Integer.parseInt("abc"); } catch (NumberFormatException e) { System.out.println("Inner: bad number"); throw e; } } catch (RuntimeException e) { System.out.println("Outer: fallback handler"); }
Learn this topic
Recommended resourcesAffiliate links · may earn us a commission