The throws Clause: Declaring Checked Exceptions
What you'll learn: How to use the throws keyword in method signatures to declare that your method might throw checked exceptions, satisfying the compiler's requirement.
Why Declare Exceptions?
When your method calls code that throws a checked exception (one that extends Exception but not RuntimeException), the compiler enforces one of two choices: either handle it with a try-catch block, or declare it in your method signature using throws. This declaration tells callers, "Hey, this method might throw this exception—be prepared!"
The throws Syntax
Place the throws keyword after the method parameters but before the opening brace:
public void readFile(String path) throws IOException {
// Code that might throw IOException
FileReader reader = new FileReader(path);
// ...
}
Multiple Exceptions
You can declare multiple exception types, separated by commas:
public void processData() throws IOException, SQLException {
// Code that might throw either exception
}
When to Use throws
Use throws when:
- Your method can't meaningfully handle the exception itself
- You want the exception to propagate up the call stack
- The calling code is better positioned to decide how to handle it
Think of throws as a contractual warning label: "Caution—this method may produce these specific problems, and I'm passing responsibility to you."
Example
public void loadConfig() throws FileNotFoundException {
readFile("config.txt"); // readFile declares IOException
}
Key Takeaway: The throws clause declares checked exceptions in your method signature, satisfying the compiler and informing callers that they must either handle or further declare these exceptions.