What is the purpose of the throw and throws keywords?
In Java, the throw and throws keywords are used for exception handling, but they serve different purposes. Here’s a breakdown of each:
- throw Keyword
Purpose: Used to explicitly throw an exception from within a method or block of code.
Where It’s Used: Inside methods, constructors, or any block of code.
Function: When an exception is thrown using throw, it immediately interrupts the normal flow of the program and transfers control to the nearest catch block (if available) or propagates the exception up the call stack.
Syntax of throw
throw new ExceptionType(“Exception message”);
Example:
public class ThrowExample { public static void main(String[] args) { try { checkAge(15); // Throws an exception } catch (IllegalArgumentException e) { System.out.println(e.getMessage()); } }
public static void checkAge(int age) {
if (age < 18) {
// Throwing an exception explicitly
throw new IllegalArgumentException("Age must be 18 or older.");
}
System.out.println("Age is valid.");
} }
Output:
Age must be 18 or older.
In this example, the throw keyword is used to throw an IllegalArgumentException when the age is less than 18.
- throws Keyword
Purpose: Used to declare exceptions that a method can throw to its caller.
Where It’s Used: In the method signature to indicate that the method may throw one or more exceptions.
Function: It provides information to the caller that the method could throw certain exceptions, and they need to handle those exceptions (either with try-catch or by propagating the exception further).
Syntax of throws
public void methodName() throws ExceptionType1, ExceptionType2 { // method body }
A method that throws exceptions must either handle them within a try-catch block or declare them using throws in its signature.
Checked exceptions must be declared using throws since they must either be caught or declared in the method signature.
Example:
public class ThrowsExample { public static void main(String[] args) { try { readFile(“file.txt”); } catch (IOException e) { System.out.println(“Error reading file: “ + e.getMessage()); } }
public static void readFile(String fileName) throws IOException {
FileReader file = new FileReader(fileName); // May throw FileNotFoundException
BufferedReader reader = new BufferedReader(file);
System.out.println(reader.readLine());
} }
Output:
Error reading file: file.txt (No such file or directory)
In this example, the method readFile declares that it may throw an IOException using the throws keyword. The calling method (main) must handle it with a try-catch block.
Key Differences between throw and throws:
When to Use:
-
Use throw when you want to explicitly create and throw an exception at a specific point in your code (e.g., validating input).
-
Use throws when you want to declare that your method may throw a certain exception, and you expect the caller to handle it.
Common Use Case:
You might combine throw and throws when writing custom exception handling for methods that need to signal error conditions explicitly, and you want the caller to be aware of these potential exceptions.
Example:
public class CustomExceptionExample { public static void main(String[] args) { try { validateData(“invalidData”); } catch (InvalidDataException e) { System.out.println(“Caught Exception: “ + e.getMessage()); } }
public static void validateData(String data) throws InvalidDataException {
if ("invalidData".equals(data)) {
throw new InvalidDataException("Invalid data provided.");
}
System.out.println("Data is valid.");
} }
class InvalidDataException extends Exception { public InvalidDataException(String message) { super(message); } }
Output:
Caught Exception: Invalid data provided.