🎓 Top 15 Udemy Courses (80-90% Discount): My Udemy Courses - Ramesh Fadatare — All my Udemy courses are real-time and project oriented courses.
▶️ Subscribe to My YouTube Channel (178K+ subscribers): Java Guides on YouTube
▶️ For AI, ChatGPT, Web, Tech, and Generative AI, subscribe to another channel: Ramesh Fadatare on YouTube
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
throwsKeyword? - Syntax
- Using
throwswith Checked Exceptions - Using
throwswith Multiple Exceptions - Custom Exceptions
- Difference Between
throwandthrows - 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
}
returnTypeis the return type of the method.methodNameis the name of the method.parameterListis 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
readFilemethod declares that it throws aFileNotFoundException. - The caller of
readFilemust handle the exception, as shown in themainmethod.
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
readFilemethod declares that it throws bothFileNotFoundExceptionandIOException. - The caller of
readFilemust handle both exceptions, as shown in themainmethod.
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
validateAgemethod declares that it throwsInvalidAgeException. - The caller of
validateAgemust handle the custom exception, as shown in themainmethod.
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