The <code>throws</code> Clause in Java
throws is part of a method's signature. It lists the checked exceptions the method might propagate without catching. Callers are forced to either catch them or declare them too. Unchecked exceptions (RuntimeException subtypes) don't need to be declared.
Syntax
public String read(Path p) throws IOException {
return Files.readString(p);
}
// Multiple types
public void writeJson(Object o, Path p) throws IOException, JsonException {
...
}
throw vs throws
throw | throws | |
|---|---|---|
| Where | Statement inside a method body | Clause on the method signature |
| Purpose | Actually raise an exception | Declare exceptions the method may propagate |
| Required for | Both checked and unchecked | Checked only (unchecked is optional) |
Overriding rules
An override can declare fewer or more specific checked exceptions than the parent β not more or broader. This preserves the caller's Liskov expectation:
class Parent {
public void work() throws IOException { ... }
}
class Child extends Parent {
@Override public void work() throws FileNotFoundException { ... } // β
subtype
@Override public void work() throws Exception { ... } // β too broad
@Override public void work() { ... } // β
none
}
Unchecked exceptions don't need declaring
public int parse(String s) {
return Integer.parseInt(s); // throws NumberFormatException β no `throws` needed
}
You can declare them as documentation, but the compiler doesn't enforce it.
Don't declare throws Exception
It defeats the purpose β callers must now catch or re-declare Exception, swallowing every specific type. Be precise about what you throw.
Common mistakes
- Declaring
throws Exceptionfor convenience β leaky abstraction. - Overriding with a broader declaration β compile error.
- Missing declaration β you throw a checked exception without declaring it β compile error "exception must be caught or declared".
- Declaring unchecked exceptions β optional, usually noise.
Related
Pillar: Java exceptions. Siblings: throw, checked vs unchecked.