CKTIS / Java
throws — declaring exceptions
The throws keyword in a method or constructor declaration specifies exception types that may escape its body. It matters especially for checked exceptions: calling code must handle them or declare that they can propagate further.
Version: Java SE 21; repository runtime, production runtime not attested
Syntax
throws ExceptionType1, ExceptionType2throws is a reserved keyword. Its clause appears after a method's or constructor's parameter list, before the body or declaration-ending semicolon. Separate types with commas; each must be a subtype of Throwable. Type variables with suitable bounds are also permitted.
If a checked exception can escape the body, the declaration must list its type or a supertype. Calling code must catch such an exception using try/catch or declare it in its own throws clause. Subtypes of RuntimeException and Error are unchecked: listing them is permitted but not required.
Do not confuse throws with throw: the former declares possible propagation, while the latter actually throws an exception. A throws clause neither throws nor handles anything and does not guarantee that an exception occurs.
When overriding a method (JLS §8.4.8.3), each declared checked exception type must match or be a subtype of a type in the overridden method's throws clause after type erasure. Otherwise, it is a compile-time error. If the condition holds only after erasure, the compiler issues an unchecked warning. For example, a non-generic method void run() throws Exception can override <E extends Exception> void run() throws E with that warning rather than an error: E erases to Exception, but before erasure, Exception is not a subtype of E.
In the example, check(false) throws the checked exception Exception, and main catches it and prints its message. The general type Exception keeps the demonstration simple; in a real API, prefer specific types that describe the possible failures.
Examples
public class ThrowsDemo {
static void check(boolean valid) throws Exception {
if (!valid) {
throw new Exception("Invalid input");
}
}
public static void main(String[] args) {
try {
check(false);
} catch (Exception e) {
System.out.println(e.getMessage());
}
}
}Result
Invalid input
The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.
Sources
- The Java Language Specification, Java SE 21, §3.9 Keywords
- The Java Language Specification, Java SE 21, §8.4.6 Method Throws
- The Java Language Specification, Java SE 21, §11.2 Compile-Time Checking of Exceptions
- The Java Language Specification, Java SE 21, §8.4.8.3 Requirements in Overriding and Hiding