Throws keyword in Java

In this tutorial, we will learn throws keyword in Java. There are many time when compiler finds some suspicious code that might throw a checked exception and warn programmers to solve exceptions. If programmer will not handle this kind of exceptions then the compiler will throw an error while compiling unreported exception XXX must be caught or declared to be thrown. In this kind of situation, we have two options whether to use a try-catch block to handle the exception or use throw keyword.

The throw keyword works in a simple way when we write it with our suspicious code it means we will not handle this exception the caller of this function will solve the exception. If our code is in the main function then JVM will handle that exception. Check out the following example program.

Example Program:

public class Example  
{ 
    public static void main(String[] args) 
    { 
        Thread.sleep(100); // a checked exception 
        System.out.println("Owlbuddy"); 
    } 
} 

Output:

Example.java:5: error: unreported exception InterruptedException; must be caught or declared to be thrown
        Thread.sleep(10000); // a checked exception 
                    ^
1 error

Do not worry In case you don’t know what is Thread. You will get detail tutorials of Multi-Threading in upcoming tutorials.

In above we have a checked exception that’s why our code is not compiling. Here we will rewrite the same code again what this time we will use throws keyword to solve this Exception.

Example Program:

public class Example  
{ 
    public static void main(String[] args) throws InterruptedException 
    { 
        Thread.sleep(100); // a checked exception 
        System.out.println("Owlbuddy"); 
    } 
}

Output:

Owlbuddy

Here is a question for you, do you know in the above example who is responsible for handling InterruptedException. If your answer is JVM then it’s right. Because here exception inside the main method.

It is important to note that using throws keyword we are not handling any exception we are just delegating the responsibility of exception handling to the caller. 

Spread the love
Scroll to Top
×