throws Keyword in Java
The throws
keyword in Java is used in method declarations to specify that the method can throw one or more exceptions. It provides a way for methods to signal that they may encounter exceptional conditions that they are not equipped to handle.
Usage
The throws
keyword is placed in the method signature after the parameter list and before the method body. It is followed by a comma-separated list of exception classes that the method can throw.
Syntax
returnType methodName(parameters) throws ExceptionType1, ExceptionType2 {
// method body
}
returnType
: The return type of the method.methodName
: The name of the method.parameters
: The parameters of the method.ExceptionType1, ExceptionType2
: The exceptions that the method can throw.
Examples
Example 1: Single Exception
public void readFile(String fileName) throws IOException {
FileReader file = new FileReader(fileName);
BufferedReader fileInput = new BufferedReader(file);
// Read file content
for (int counter = 0; counter < 3; counter++)
System.out.println(fileInput.readLine());
fileInput.close();
}
In this example, the readFile
method declares that it can throw an IOException
. This indicates that the method may encounter an input/output error that it cannot handle internally.
Example 2: Multiple Exceptions
public void processFile(String fileName) throws IOException {
FileReader file = new FileReader(fileName);
BufferedReader fileInput = new BufferedReader(file);
// Read file content
for (int counter = 0; counter < 3; counter++)
System.out.println(fileInput.readLine());
fileInput.close();
}
Here, the processFile
method declares that it can throw both IOException
and FileNotFoundException
. This informs the caller that the method may encounter either of these exceptions.
Example 3: Custom Exception
public class CustomException extends Exception {
public CustomException(String message) {
super(message);
}
}
public void validateAge(int age) throws CustomException {
if (age < 18) {
throw new CustomException("Age must be 18 or older.");
}
System.out.println("Age is valid.");
}
In this example, a custom exception CustomException
is created. The validateAge
method declares that it can throw this custom exception if the age is less than 18.
Tips and Best Practices
- Declare Specific Exceptions: Declare the most specific exceptions possible rather than using a generic
Exception
class. This makes the code more readable and maintainable.public void method() throws IOException, SQLException { // method body }
- Document Exceptions: Always document the exceptions that a method can throw using Javadoc comments. This helps other developers understand the potential risks and handle them appropriately.
/** * Reads a file and prints its content. * * @param fileName the name of the file to read * @throws IOException if an I/O error occurs */ public void readFile(String fileName) throws IOException { // method body }
- Use
throws
Judiciously: Only use thethrows
keyword when the method cannot handle the exception internally. If possible, handle exceptions within the method to provide a more robust and user-friendly application.public void readFile(String fileName) { try { FileReader file = new FileReader(fileName); BufferedReader fileInput = new BufferedReader(file); // Read file content for (int counter = 0; counter < 3; counter++) System.out.println(fileInput.readLine()); fileInput.close(); } catch (IOException e) { System.err.println("An error occurred: " + e.getMessage()); } }
- Propagate Exceptions: When propagating exceptions, ensure that the calling method is capable of handling them or further propagates them up the call stack.