Throws clause in java – Exception handling

Use of throws keyword in Java

1. The throws keyword is used in method declaration, in order to explicitly specify the exceptions that a particular method might throw. When a method declaration has one or more exceptions defined using throws clause then the method-call must handle all the defined exceptions.
2. When defining a method you must include a throws clause to declare those exceptions that might be thrown but doesn’t get caught in the method.
3. If a method is using throws clause along with few exceptions then this implicitly tells other methods that – “ If you call me, you must handle these exceptions that I throw”.

Syntax of Throws in java:

void MethodName() throws ExceptionName{


public void sample() throws IOException{
     //if (somethingWrong)
     IOException e = new IOException();
     throw e;
     //More Statements

Note: In case a method throws more than one exception, all of them should be listed in throws clause. PFB the example to understand the same.

public void sample() throws IOException, SQLException

The above method has both IOException and SQLException listed in throws clause. There can be any number of exceptions defined using throws clause.

Complete Example of Java throws Clause

class Demo
   static void throwMethod() throws NullPointerException
       System.out.println ("Inside throwMethod");
       throw new NullPointerException ("Demo"); 
   public static void main(String args[])
       catch (NullPointerException exp)
          System.out.println ("The exception get caught" +exp);

The output of the above program is:

Inside throwMethod
The exception get caught java.lang.IllegalAccessException: Demo

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s