In Java, throw and throws are two different keywords that are used for exception handling.
throw is used to throw an exception explicitly from a method or block of code. It is used when a program encounters an exceptional condition that cannot be handled by the program, and the program needs to terminate abruptly. When a throw statement is executed, it throws an object of a specific exception type. The thrown exception can be caught and handled by a try-catch block in the calling method or propagated up the call stack until it is caught and handled by a try-catch block or until it reaches the top of the call stack, where the JVM will terminate the program and print the stack trace of the exception.
Here's an example of how to use the throw keyword in Java:
public class CustomException extends Exception {
public CustomException(String message) {
super(message);
}
}
public class Example {
public static void main(String[] args) {
try {
int num = -1;
if (num < 0) {
throw new CustomException("Number cannot be negative");
}
} catch (CustomException e) {
System.out.println(e.getMessage());
}
}
}
Throws:
On the other hand, throws is used to declare the exceptions that can be thrown by a method. It is used in the method signature to indicate that the method may throw one or more exceptions, which need to be caught and handled by the calling method or propagated up the call stack until they are caught and handled.
Here's an example of how to use the throws keyword in Java:
public class Example {
public static void main(String[] args) {
try {
int num = -1;
if (num < 0) {
throw new IllegalArgumentException("Number cannot be negative");
}
} catch (IllegalArgumentException e) {
System.out.println(e.getMessage());
}
}
public static void doSomething() throws IllegalArgumentException {
// code that may throw an IllegalArgumentException
}
}
In this example, we have a main() method that throws an instance of IllegalArgumentException if the value of num is less than 0. The exception is caught and handled in the catch block by printing the message associated with the exception object.
We also have a doSomething() method that declares that it may throw an IllegalArgumentException by using the throws keyword. If the doSomething() method throws an IllegalArgumentException, the exception will be propagated up the call stack until it is caught and handled by a try-catch block.
In summary, throw is used to throw an exception explicitly, while throws is used to declare the exceptions that can be thrown by a method. Both of these keywords are essential for effective exception handling in Java.