Throw and Throws Keywords in Java
In Java, exceptions are used to handle abnormal situations that can occur during the execution of a program. The throw and throws keywords are used for throwing exceptions explicitly. They allow you to control exception handling in your programs. Let's explore both keywords in detail.
1. The throw Keyword
The throw keyword is used to throw an exception explicitly in Java. It allows you to create your own exceptions and throw them from a method or a block of code. Once an exception is thrown, the flow of control is transferred to the nearest catch block, or the program terminates if there is no catch block.
Syntax of throw Keyword
throw new ExceptionType("Error message");
Example of Using throw
In this example, we use the throw keyword to throw an exception manually when a value is negative.
public class Main {
public static void main(String[] args) {
try {
checkNumber(-5); // Passing a negative number
} catch (IllegalArgumentException e) {
System.out.println("Caught exception: " + e.getMessage());
}
}
static void checkNumber(int number) {
if (number < 0) {
throw new IllegalArgumentException("Number cannot be negative");
} else {
System.out.println("Number is positive");
}
}
}
Output:
Caught exception: Number cannot be negative
Explanation:
- The
checkNumbermethod checks if the passed number is negative. - If the number is negative, it throws an
IllegalArgumentExceptionusing thethrowkeyword. - The exception is caught in the
catchblock and the error message is printed.
2. The throws Keyword
The throws keyword is used to declare exceptions that a method may throw. This allows you to specify which exceptions the method is capable of throwing without having to handle them in the method itself. It is used in the method signature.
Syntax of throws Keyword
returnType methodName() throws ExceptionType1, ExceptionType2 {
// method implementation
}
Example of Using throws
In this example, we use the throws keyword to declare that a method may throw an IOException exception.
import java.io.IOException;
public class Main {
public static void main(String[] args) {
try {
readFile(); // Calling a method that throws an exception
} catch (IOException e) {
System.out.println("Caught exception: " + e.getMessage());
}
}
static void readFile() throws IOException {
throw new IOException("File not found");
}
}
Output:
Caught exception: File not found
Explanation:
- The
readFilemethod is declared to throw anIOExceptionusing thethrowskeyword. - Inside the method, an
IOExceptionis thrown manually using thethrowkeyword. - The exception is caught in the
catchblock of themainmethod, and the error message is printed.
3. Difference Between throw and throws
Both throw and throws are related to exceptions, but they are used in different contexts:
throwis used to explicitly throw an exception from a method or a block of code.throwsis used in a method declaration to specify the exceptions that the method may throw during execution.
4. Example of Combining throw and throws
In this example, we combine both throw and throws keywords. The main method calls a method that may throw an exception, and the main method itself declares that it may throw an exception using the throws keyword.
public class Main {
public static void main(String[] args) throws Exception {
try {
processData(-10); // Calling a method that throws an exception
} catch (IllegalArgumentException e) {
System.out.println("Caught exception: " + e.getMessage());
}
}
static void processData(int number) throws IllegalArgumentException {
if (number < 0) {
throw new IllegalArgumentException("Number cannot be negative");
}
System.out.println("Processing number: " + number);
}
}
Output:
Caught exception: Number cannot be negative
Explanation:
- The
processDatamethod checks if the passed number is negative and throws anIllegalArgumentExceptionusing thethrowkeyword. - The
mainmethod callsprocessDataand declares that it may throw an exception using thethrowskeyword. - The exception is caught in the
catchblock and the error message is printed.
5. Conclusion
The throw and throws keywords are essential tools for exception handling in Java. The throw keyword allows you to throw an exception explicitly, while the throws keyword is used to declare exceptions that a method can throw. Understanding these keywords is crucial for creating robust and error-resistant Java programs that can handle unexpected situations gracefully.