Throws Keyword in Java
intermediate· Exceptions · Error Handling
Problem
The throws clause in a method signature declares that a checked exception might come out of that method, shifting the obligation to handle it onto whoever calls it.
Declare a method that can throw a checked exception without catching it internally, and handle it in the caller instead.
Input
fail = true
Output
Caller handled: Config read was interrupted
Java Program
Java
public class ThrowsKeywordDemo {
static void readConfig(boolean fail) throws InterruptedException { // no internal catch — propagates to the caller
if (fail) {
throw new InterruptedException("Config read was interrupted");
}
System.out.println("Config loaded successfully");
}
public static void main(String[] args) {
try {
readConfig(true);
} catch (InterruptedException e) {
System.out.println("Caller handled: " + e.getMessage());
}
}
}Output
Caller handled: Config read was interrupted
Core Logic
Declaring throws on the method signature, without a try/catch inside it, lets the exception pass straight through to whichever method actually calls it.
How It Works
- 1
readConfig(boolean fail) throws InterruptedExceptiondeclares that this method might throw a checked exception, without handling it anywhere inside its own body. - 2When
failistrue, the method throws directly — there's no internaltry/catchto intercept it here. - 3Because the exception isn't caught inside
readConfig(), it propagates straight out to whoever called it. - 4
mainis the one that actually wraps the call intry/catch, making it the method responsible for handling the failure.
Calling
readConfig(true) throws immediately; since readConfig itself never catches it, main's catch block is what finally handles it, printing "Caller handled: Config read was interrupted".💡
Key Point: throws only declares that a checked exception can escape a method — it's the caller, not the declaring method, that ends up doing the actual catching, unlike throw, which is the statement that raises the exception in the first place.
Key Concepts
throws clausechecked exceptionexception propagation