Interview Q&A · Java · 4 questions in this topic
throw, throws and Rethrowing — Java Interview Q&A
How to raise failures explicitly, declare them in signatures, and propagate them with chaining. Part of Exception Handling · 294 questions in the Java bank.
What does the throw keyword do?
Answer
The throw statement explicitly raises a Throwable object, immediately stopping normal execution in the current block. Control then propagates outward to the nearest matching catch, unwinding method calls as needed. If no handler is found, the default handler prints the failure details and ends the thread.
Example
void validate(int age) { if (age < 0) { throw new IllegalArgumentException("Age must not be negative"); } }
Can code follow a throw statement?
Answer
No, statements placed directly after a throw on a path where they could never execute are rejected as unreachable code. The compiler detects that execution always leaves at the throw and reports a compile error. Any follow-up logic must go into a catch or finally block, or before the throw under a condition.
What does throws do?
Answer
The throws clause in a method signature declares the checked exception types that the method may propagate to its callers. It shifts responsibility for handling from the method itself to whoever calls it, making the failure part of the method contract. Unchecked types may be listed for documentation, but the compiler requires the clause only for checked exceptions.
Example
void save(String data) throws java.io.IOException { java.nio.file.Files.writeString(java.nio.file.Path.of("out.txt"), data); }
Can an exception be rethrown from a catch block?
Answer
Yes, a catch block can throw the caught exception again after logging it, cleaning up, or translating it. Wrapping it in a new exception with the original passed as the cause preserves the full chain for debugging. Since Java 7, precise rethrow lets a method rethrow a caught final-like parameter without widening the throws clause to Exception.
Example
try { loadFile(); } catch (java.io.IOException e) { System.err.println("Load failed"); throw new IllegalStateException("Startup aborted", e); }
💡 Always chain the original as the cause so the stack trace shows the root failure.
Learn this topic
Recommended resourcesAffiliate links · may earn us a commission