Purpose:
throw
keyword is used to explicitly create and throw an exception. It is primarily used to hand over a custom or user-defined exception object to the JVM.throw
statement, no code should be placed because it will result in a compile-time error; the flow of execution immediately stops and control is passed to the nearest catch block.Usage:
throw
keyword is used when you want to manually trigger an exception based on certain conditions or business logic.Advantages:
Disadvantages:
public class Test1 {
public static void checkAge(int age) {
if (age < 18) {
throw new IllegalArgumentException("Age must be 18 or older.");
}
System.out.println("Age is valid.");
}
public static void main(String[] args) {
try {
checkAge(15); // This will throw an exception
} catch (IllegalArgumentException e) {
System.out.println("Exception message: " + e.getMessage());
// Catch and handle the exception
}
}
}
Exception message: Age must be 18 or older.
Explanation:
checkAge
method throws an IllegalArgumentException
if the age is less than 18. The exception is then caught and handled in the main
method.Purpose:
throws
keyword is used in the method signature to declare that a method might throw one or more exceptions. It delegates the responsibility of handling the exception to the method's caller.Usage:
throws
keyword is used when a method is not intended to handle an exception but wants to signal to the caller that an exception might occur.try-catch
for handling exceptions rather than just declaring them with throws
, as throws
does not prevent abnormal program termination.Syntax:
public void methodName() throws ExceptionType1, ExceptionType2 {
// Method body
}
Key Points:
throws
keyword delegates the responsibility of exception handling to the method that calls it.throws
keyword can be used with both methods and constructors but not with classes.Advantages:
Disadvantages:
xxxxxxxxxx
import java.io.*;
public class Test2 {
public static void main(String[] args) {
try {
readFile("nonexistentfile.txt");
} catch (IOException e) {
System.out.println("Caught: " + e.getMessage());
}
}
public static void readFile(String fileName) throws IOException {
FileReader file = new FileReader(fileName);
BufferedReader fileInput = new BufferedReader(file);
throw new IOException("File not found");
}
}
Caught: File not found
Explanation:
readFile
method declares that it throws an IOException
. The main
method calls readFile
, and since the method might throw an exception, it must handle it with a try-catch
block.