What is the difference between throw and throws?
In Java, both `throw` and `throws` are keywords used in exception handling, but they serve different purposes. Understanding their distinctions is crucial for robust error management in your applications.
The 'throw' Keyword
The throw keyword is used to explicitly throw a single instance of an exception. When throw is executed, the normal flow of the program is interrupted, and the control is transferred to the nearest enclosing catch block that can handle the thrown exception. If no such catch block is found, the exception propagates up the call stack.
Key characteristics of throw:
- Used within a method body.
- Followed by an instance of an exception class (e.g.,
new IOException("Error message")). - Used for throwing a single exception at a time.
- It's a statement.
Example of 'throw'
public class ThrowExample {
static void validateAge(int age) {
if (age < 18) {
// Explicitly throwing an ArithmeticException
throw new ArithmeticException("Not eligible to vote");
} else {
System.out.println("Welcome to vote");
}
}
public static void main(String args[]) {
try {
validateAge(15);
} catch (ArithmeticException e) {
System.out.println("Caught exception: " + e.getMessage());
}
validateAge(20);
}
}
The 'throws' Keyword
The throws keyword is used in the method signature to declare the types of checked exceptions that a method might throw. It informs the caller of the method that certain exceptions might occur during the method's execution and that the caller should either handle these exceptions or declare them again. It essentially delegates the responsibility of handling the exception to the calling method.
Key characteristics of throws:
- Used with the method signature.
- Followed by one or more exception class names (e.g.,
IOException, SQLException). - Used for declaring multiple exceptions, separated by commas.
- It's part of the method's contract.
Example of 'throws'
import java.io.IOException;
public class ThrowsExample {
// Declaring that this method might throw an IOException
static void readFile(String filePath) throws IOException {
// Simulate an operation that might throw IOException
if (filePath == null || filePath.isEmpty()) {
throw new IOException("File path cannot be empty");
}
System.out.println("Reading file: " + filePath);
// ... actual file reading logic
}
public static void main(String args[]) {
try {
readFile("data.txt");
readFile(null);
} catch (IOException e) {
System.out.println("Caught exception in main: " + e.getMessage());
}
}
}
Comparison Table: throw vs. throws
| Feature | throw | throws |
|---|---|---|
| Purpose | Explicitly throws an exception instance. | Declares that a method might throw one or more exceptions. |
| Usage Location | Inside the method body (as a statement). | In the method signature (part of the method declaration). |
| Syntax | `throw new ExceptionType("message");` | `public void method() throws ExceptionType1, ExceptionType2 { ... }` |
| Argument/Value | Requires a single instance of `Throwable` class. | Requires one or more `Throwable` class names (comma-separated). |
| Number of Exceptions | Used to throw a single exception at a time. | Used to declare multiple exceptions (e.g., `IOException, SQLException`). |
| Responsibility | Executes the exception-throwing operation. | Delegates exception handling responsibility to the caller. |
| Type of Exceptions | Can throw both checked and unchecked exceptions. | Primarily used for checked exceptions; for unchecked exceptions, it's optional but good practice for documentation. |