throw and throws in Java
Exception handling is a critical mechanism in Java used to handle runtime errors, ensuring the normal flow of the application can be maintained or gracefully terminated. The throw and throws keywords are central to this mechanism, but they serve completely distinct purposes.
The throw Keyword
The throw keyword is used to explicitly trigger (throw) an exception from any method or block of code.
You use throw when your program encounters an exceptional state—such as invalid input, failed validations, or missing resources—and you want to signal an error rather than continuing with invalid data.
Syntax and Usage
You can throw any instance of Throwable (usually a subclass of Exception or RuntimeException).
public class Validator {
public void checkAge(int age) {
if (age < 18) {
// Explicitly instantiating and throwing a runtime exception
throw new IllegalArgumentException("Age must be 18 or older to register.");
} else {
System.out.println("Registration successful.");
}
}
}
Key Characteristics of throw
- Execution Flow: When a
throwstatement executes, the normal flow of the program halts immediately. The nearest enclosingtry-catchblock that handles the exception is searched. If none is found, the thread terminates. - Only One Object: You can only throw a single exception object at a time.
- Custom Exceptions: It is heavily used to throw custom, user-defined exceptions.
class InsufficientFundsException extends Exception {
public InsufficientFundsException(String msg) { super(msg); }
}
public void withdraw(double amount) throws InsufficientFundsException {
if (balance < amount) {
throw new InsufficientFundsException("Not enough balance: " + balance);
}
balance -= amount;
}
The throws Keyword
The throws keyword is used in a method signature to declare that a method might throw one or more exceptions during its execution.
It does not actually throw an exception; it delegates the responsibility of handling the exception to the caller of the method. This is a core part of Java's Checked Exception requirement.
Syntax and Usage
If a method contains code that could throw a Checked Exception (like IOException or SQLException), the method must either handle it with a try-catch block, or declare it using throws.
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
public class FileHandler {
// Declaring that this method might throw an IOException
// The caller of readFile() is now forced to handle it.
public void readFile(String path) throws IOException {
File file = new File(path);
// FileReader constructor can throw FileNotFoundException (a subclass of IOException)
FileReader fr = new FileReader(file);
fr.close();
}
}
Key Characteristics of throws
- Method Signature:
throwsis always appended to the method signature, just before the method body{. - Multiple Exceptions: A method can declare multiple exceptions, separated by commas (e.g.,
throws IOException, SQLException). - Checked vs. Unchecked: While you can declare unchecked exceptions (like
NullPointerExceptionorRuntimeException) usingthrowsfor documentation purposes, the compiler only forces you to declare Checked Exceptions.
throw vs. throws: The Core Differences
| Feature | throw | throws |
| :--- | :--- | :--- |
| Purpose | Used to explicitly trigger an exception. | Used to declare that a method might throw an exception. |
| Location | Used inside a method body or block of code. | Used in the method signature. |
| Quantity | Can throw only one exception object at a time. | Can declare multiple exceptions (comma-separated). |
| Followed by | Followed by an instance (object) of an exception. | Followed by exception class names. |
| Delegation | The action of creating the error state. | Delegates the error handling responsibility to the caller. |
Practical Example: Combining Both
A robust application often uses both: throws to declare the contract of a method, and throw to enforce business logic inside it.
import java.io.IOException;
public class NetworkService {
// 1. 'throws' declares the method might fail with connection issues
public void connect(String ipAddress) throws IOException {
if (ipAddress == null || ipAddress.isEmpty()) {
// 2. 'throw' is used for an immediate, unchecked logic error
throw new IllegalArgumentException("IP Address cannot be null or empty.");
}
boolean networkAvailable = checkNetwork();
if (!networkAvailable) {
// 3. 'throw' is used to trigger the checked exception declared above
throw new IOException("Failed to establish connection to " + ipAddress);
}
System.out.println("Connected.");
}
private boolean checkNetwork() { return false; } // Simulated
}