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

throw, throws and Rethrowing — Java Interview Q&A

All Java topics

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

Example.javajava
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

Example.javajava
void save(String data) throws java.io.IOException {
    java.nio.file.Files.writeString(java.nio.file.Path.of("out.txt"), data);
}

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