Throw Keyword
The throw
keyword is used to explicitly throw an exception. It can be used to throw both checked and unchecked exceptions, and it is typically used within a method or a block of code. It is often used to enforce specific error conditions within methods.
public class ThrowExample {
public static void main(String[] args) {
try {
validateAge(15); // This will throw an exception
} catch (IllegalArgumentException e) {
System.out.println("Exception caught: " + e.getMessage());
}
}
public static void validateAge(int age) {
if (age < 18) {
throw new IllegalArgumentException("Age must be 18 or older.");
}
}
}
Throws Keyword
The throws
keyword is used in a method signature to declare that a method might throw one or more exceptions. This informs the caller of the method that they need to handle these exceptions, either with a try-catch block or by further declaring them using throws
.
It can declare multiple exceptions separated by commas. It is primarily used with checked exceptions to satisfy the compiler’s requirements. However, you can also use throws
with unchecked exceptions, although it’s not necessary since the compiler does not enforce handling of unchecked exceptions.
import java.io.*;
public class CombinedExample {
public static void main(String[] args) {
try {
processFile("example.txt");
} catch (IOException e) {
System.out.println("Exception caught: " + e.getMessage());
}
}
public static void processFile(String fileName) throws IOException {
if (fileName == null) {
throw new IllegalArgumentException("File name cannot be null");
}
FileReader file = new FileReader(fileName);
BufferedReader reader = new BufferedReader(file);
String line = reader.readLine();
System.out.println(line);
reader.close();
}
}