In Java, throw
, throws
, and finally
are related to exception handling, but they have very different purposes.
1. throw
- Purpose: Used inside a method to actually throw an exception object.
- Syntax:
throw new ExceptionType("message");
- Key Points:
- Works with a single exception instance at a time.
- Control jumps immediately to the nearest matching
catch
block or to the caller if unhandled. - You can throw either checked or unchecked exceptions.
Example:
public void validateAge(int age) {
if (age < 18) {
throw new IllegalArgumentException("Age must be 18 or above");
}
}
2. throws
- Purpose: Declares that a method might throw certain exceptions, so callers must handle or rethrow them.
- Syntax:
returnType methodName(...) throws ExceptionType1, ExceptionType2 { // method code }
- Key Points:
- Goes in the method signature, not inside the method body.
- Required for checked exceptions unless handled inside the method.
- Multiple exception types can be declared (comma-separated).
Example:
public void readFile(String path) throws IOException {
FileReader fr = new FileReader(path);
}
3. finally
- Purpose: A block that always executes after
try
andcatch
, regardless of whether an exception occurred. - Syntax:
try { // code that may throw exceptions } catch (Exception e) { // handle exception } finally { // cleanup code }
- Key Points:
- Used for cleanup (closing files, releasing resources).
- Runs even if there’s a
return
intry
orcatch
. - Does not run if the JVM shuts down abruptly (e.g.,
System.exit()
).
Example:
try {
FileReader fr = new FileReader("file.txt");
} catch (IOException e) {
System.out.println("File not found");
} finally {
System.out.println("This always runs");
}
Quick Comparison Table
Keyword | Where Used | Meaning | Example |
---|---|---|---|
throw | Inside a method | Actually throws an exception object | throw new IOException(); |
throws | In method declaration | Declares possible exceptions a method can throw | void m() throws IOException |
finally | After try/catch block | Code that always runs (for cleanup) | finally { closeFile(); } |