What is the difference between `throw` and `throws`?
throw
: It is used to explicitly throw an exception from a method or a block of code. It is followed by an instance of the Throwable
class or its subclasses.
Example:
public void validateAge(int age) {
if (age < 18) {
throw new IllegalArgumentException("Age must be 18 or above");
}
}
throws
: It is used in a method declaration to indicate that the method might throw one or more exceptions. This informs the caller of the method to handle or declare these exceptions.
Example:
public void readFile(String filePath) throws IOException {
FileReader reader = new FileReader(filePath);
// Code to read the file
}
Key Difference:
throw
is used to throw an exception during the program’s execution.throws
is used to declare exceptions that a method might throw, ensuring the caller handles them.