Exception handling in Java helps manage runtime errors and prevents the program from crashing, allowing the normal flow of the application to continue. Java provides specific keywords to handle and manage exceptions effectively.
- throw is used to explicitly throw an exception.
- throws is used to declare exceptions in a method signature.
throw Keyword
The throw keyword in Java is used to explicitly throw an exception from a method or any block of code. We can throw either checked or unchecked exception. The throw keyword is mainly used to throw custom exceptions.
- Written inside a method or block.
- Stops program execution immediately after execution.
Syntax:
throw new ExceptionName("message");
Example: This example demonstrates where an exception is thrown, caught and rethrown inside a method.
class Geeks {
static void fun()
{
try {
throw new NullPointerException("demo");
}
catch (NullPointerException e) {
System.out.println("Caught inside fun().");
throw e; // rethrowing the exception
}
}
public static void main(String args[])
{
try {
fun();
}
catch (NullPointerException e) {
System.out.println("Caught in main.");
}
}
}
Output
Caught inside fun(). Caught in main.
Explanation: The above example demonstrates the use of the throw keyword to explicitly throw a NullPointerException. The exception is caught inside the fun() method and rethrown, where it is then caught in the main() method.
Example: Throwing an arithmetic exception
class Geeks {
public static void main(String[] args){
int numerator = 1;
int denominator = 0;
if (denominator == 0) {
// Manually throw an ArithmeticException
throw new ArithmeticException("Cannot divide by zero");
} else {
System.out.println(numerator / denominator);
}
}
}
Output:
Hangup (SIGHUP)
Exception in thread "main" java.lang.ArithmeticException: Cannot divide by zero at Geeks.main(Geeks.java:9)
Explanation: The above example demonstrates an exception using throw, where an ArithmeticException is explicitly thrown due to division by zero.
throws Keyword
throws is a keyword in Java that is used in the signature of a method to indicate that this method might throw one of the listed type exceptions. The caller to these methods has to handle the exception using a try-catch block.
- Declares possible exceptions.
- Mainly used with checked exceptions.
Syntax:
returnType methodName() throws ExceptionName
Example 1: Unhandled Exception
class Geeks {
public static void main(String[] args)
{
Thread.sleep(10000);
System.out.println("Hello Geeks");
}
}
Output:
error: unreported exception InterruptedException; must be caught or declared to be thrownExplanation: In the above program, we are getting compile time error because there is a chance of exception if the main thread is going to sleep, other threads get the chance to execute the main() method which will cause InterruptedException.
Example 2: Using throws to Handle Exception
class Geeks {
public static void main(String[] args)
throws InterruptedException
{
Thread.sleep(10000);
System.out.println("Hello Geeks");
}
}
Output:
Hello GeeksExplanation: In the above program, by using the throws keyword we handled the InterruptedException and we will get the output as Hello Geeks.
Example 3: Throwing an Exception with throws
class Geeks {
static void fun() throws IllegalAccessException
{
System.out.println("Inside fun(). ");
throw new IllegalAccessException("demo");
}
public static void main(String args[])
{
try {
fun();
}
catch (IllegalAccessException e) {
System.out.println("Caught in main.");
}
}
}
Output
Inside fun(). Caught in main.
Explanation: The above example throwing a IllegalAccessException from a method and handling it in the main method using a try-catch block.
throw Vs throws
The main differences between throw and throws in Java are as follows:
| throw | throws |
|---|---|
| Used to explicitly throw an exception. | Used to declare exceptions. |
| Written inside a method body. | Written in the method signature. |
| Throws a single exception object. | Can declare multiple exceptions. |
| Followed by an exception object. | Followed by exception class names. |
Used with new keyword. | Does not use new keyword. |
| Stops execution immediately after throwing exception. | Only informs that an exception may occur. |
| Used for manual exception handling. | Used to delegate exception handling responsibility. |
| Can throw checked and unchecked exceptions. | Mainly used for checked exceptions. |
| Requires exception object creation. | Does not create exception objects. |
Example: throw new IOException(); | Example: void test() throws IOException |