In Java, throw and throws are important keywords used in exception handling to manage runtime and compile-time errors efficiently.
The throw keyword in Java is used to explicitly throw an exception from a method or a block of code. It helps indicate an abnormal condition manually.
throw new ExceptionType("Error Message");
class Demo {
public static void main(String[] args) {
int age = 15;
if (age < 18) {
throw new ArithmeticException("Not eligible for voting");
} else {
System.out.println("Eligible for voting");
}
}
}
Output:
Exception in thread "main" java.lang.ArithmeticException: Not eligible for voting
The throws keyword is used in the method declaration to specify the exceptions that a method may throw during execution. It alerts the caller of possible exceptions.
returnType methodName() throws ExceptionType1, ExceptionType2 {
// code
}
import java.io.*;
class Demo {
void readFile() throws IOException {
FileReader file = new FileReader("data.txt");
BufferedReader fileInput = new BufferedReader(file);
System.out.println(fileInput.readLine());
}
public static void main(String[] args) throws IOException {
Demo obj = new Demo();
obj.readFile();
}
}
Output:
FileNotFoundException: data.txt (No such file or directory)
| throw | throws |
|---|---|
| Used to explicitly throw an exception. | Used in method declaration to declare exceptions. |
| Followed by a single exception instance. | Followed by one or more exception classes. |
| Occurs within the method body. | Occurs in the method signature. |
| Checked and unchecked exceptions can be thrown. | Declares checked exceptions only. |
Use throw when you want to manually generate exceptions to indicate errors in your logic.
Use throws when a method may throw exceptions, and you want to inform the method caller about it.
Always prefer using specific exception types (like IOException, NullPointerException) instead of the generic Exception class.
Handle exceptions gracefully using try-catch blocks to improve user experience and maintain code flow.