Introduction
The throws
keyword in Java is used in method declarations to specify that a method can throw one or more exceptions. It informs the caller of the method about the types of exceptions that might be thrown, so they can handle them appropriately. This is essential for checked exceptions, which must be either caught or declared in the method signature using the throws
keyword.
Table of Contents
- What is the
throws
Keyword? - Syntax
- Using
throws
with Checked Exceptions - Using
throws
with Multiple Exceptions - Custom Exceptions
- Difference Between
throw
andthrows
- Complete Example Program
- Conclusion
1. What is the throws Keyword?
The throws
keyword is used in a method's declaration to indicate that the method can throw exceptions. This helps in propagating exceptions to the caller method, ensuring that the exceptions are either handled or further declared.
2. Syntax
The syntax for the throws
keyword is as follows:
returnType methodName(parameterList) throws ExceptionType1, ExceptionType2, ... {
// Method body
}
returnType
is the return type of the method.methodName
is the name of the method.parameterList
is the list of parameters for the method.ExceptionType1, ExceptionType2, ...
are the types of exceptions that the method might throw.
3. Using throws with Checked Exceptions
Checked exceptions must be either caught within the method or declared in the method signature using the throws
keyword.
Example:
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
public class ThrowsExample {
public static void main(String[] args) {
try {
readFile("example.txt");
} catch (FileNotFoundException e) {
System.out.println("Caught exception: " + e.getMessage());
}
}
public static void readFile(String fileName) throws FileNotFoundException {
File file = new File(fileName);
FileReader fr = new FileReader(file);
System.out.println("File read successfully");
}
}
Output:
Caught exception: example.txt (No such file or directory)
Explanation:
- The
readFile
method declares that it throws aFileNotFoundException
. - The caller of
readFile
must handle the exception, as shown in themain
method.
4. Using throws with Multiple Exceptions
A method can declare multiple exceptions in its signature using the throws
keyword.
Example:
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
public class MultipleThrowsExample {
public static void main(String[] args) {
try {
readFile("example.txt");
} catch (FileNotFoundException e) {
System.out.println("Caught FileNotFoundException: " + e.getMessage());
} catch (IOException e) {
System.out.println("Caught IOException: " + e.getMessage());
}
}
public static void readFile(String fileName) throws FileNotFoundException, IOException {
File file = new File(fileName);
FileReader fr = new FileReader(file);
fr.read();
System.out.println("File read successfully");
}
}
Output:
Caught FileNotFoundException: example.txt (No such file or directory)
Explanation:
- The
readFile
method declares that it throws bothFileNotFoundException
andIOException
. - The caller of
readFile
must handle both exceptions, as shown in themain
method.
5. Custom Exceptions
You can create custom exceptions and use the throws
keyword to declare them in method signatures.
Example:
class InvalidAgeException extends Exception {
public InvalidAgeException(String message) {
super(message);
}
}
public class CustomExceptionExample {
public static void main(String[] args) {
try {
validateAge(15);
} catch (InvalidAgeException e) {
System.out.println("Caught custom exception: " + e.getMessage());
}
}
public static void validateAge(int age) throws InvalidAgeException {
if (age < 18) {
throw new InvalidAgeException("Age must be 18 or older.");
}
System.out.println("Age is valid.");
}
}
Output:
Caught custom exception: Age must be 18 or older.
Explanation:
- The
validateAge
method declares that it throwsInvalidAgeException
. - The caller of
validateAge
must handle the custom exception, as shown in themain
method.
6. Difference Between throw and throws
throw
: Used to explicitly throw an exception.throw new ExceptionType("Exception message");
throws
: Used in the method signature to declare that the method might throw one or more exceptions.returnType methodName(parameterList) throws ExceptionType1, ExceptionType2, ... { // Method body }
Example:
public class ThrowVsThrowsExample {
public static void main(String[] args) {
try {
methodThatThrows();
} catch (Exception e) {
System.out.println("Caught exception: " + e.getMessage());
}
}
public static void methodThatThrows() throws Exception {
throw new Exception("This is an exception");
}
}
Output:
Caught exception: This is an exception
7. Complete Example Program
Here is a complete program that demonstrates the use of the throws
keyword with both built-in and custom exceptions, as well as handling multiple exceptions.
Example Code:
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
// Custom exception
class InvalidAgeException extends Exception {
public InvalidAgeException(String message) {
super(message);
}
}
public class ThrowsKeywordExample {
public static void main(String[] args) {
// Example 1: Using throws with built-in exception
try {
readFile("example.txt");
} catch (FileNotFoundException e) {
System.out.println("Caught FileNotFoundException: " + e.getMessage());
} catch (IOException e) {
System.out.println("Caught IOException: " + e.getMessage());
}
// Example 2: Using throws with custom exception
try {
validateAge(15);
} catch (InvalidAgeException e) {
System.out.println("Caught custom exception: " + e.getMessage());
}
}
public static void readFile(String fileName) throws FileNotFoundException, IOException {
File file = new File(fileName);
FileReader fr = new FileReader(file);
fr.read();
System.out.println("File read successfully");
}
public static void validateAge(int age) throws InvalidAgeException {
if (age < 18) {
throw new InvalidAgeException("Age must be 18 or older.");
}
System.out.println("Age is valid.");
}
}
Output:
Caught FileNotFoundException: example.txt (No such file or directory)
Caught custom exception: Age must be 18 or older.
8. Conclusion
The throws
keyword in Java is used for propagating exceptions up the call stack. By declaring exceptions in method signatures, it allows for better handling of exceptional conditions and more robust error management. Understanding the difference between throw
and throws
, and knowing how to use them effectively, is crucial for writing reliable Java code.
Happy coding!
Comments
Post a Comment
Leave Comment