Throw and Throws keywords in java

In the previous post, we have seen the usage of multiple catch blocks in java. In this post, we will learn about the throw and throws keyword.

If asked about the difference between them, one should not say singular and plural.Well, this was on a lighter note.

In java, these are the keywords which got different jobs to do.

Let’s understand them one by one with examples.

Throw keyword in java:

The throw keyword is used to throw an exception explicitly that means we can throw a custom exception using this keyword. It is possible to throw either checked or unchecked exception with throw keyword.

Let’s understand with an example.

Output: Exception in thread “main” java.lang.NullPointerException: Name seems to be blank

In the above example, if name is blank then we are throwing exception explicitly.


Throws Keyword in java:

As we have seen before , there are mainly 2 kind of exceptions which are checked and unchecked exceptions. Checked exceptions occur at compile time that means programmer has to handle these exception ,otherwise program will not be compiled.

Unchecked exceptions occur at run time that means these will not be checked at compile time.

So for handling compile time error, we use throws keyword. This keyword is used in method signature and multiple exceptions can be declared with this.

Syntax of throws keyword:

We have declared IOException and ClassNotFoundException in method signature using Throws keyword.

Let’s understand with an example.

Suppose, we are reading a file. For handling file it has added IOException in method signautre.We have also added ClassNotFoundException , just to show that it  handles multiple exceptions.

We can say that it can be considered as alternative of try-catch block.

As you can observe, we have called a method readFile which is handling IOException and classnotFound exception using Throws keyword. The point to note is that the calling method will also be forced to declare the same exceptions (In this case main method).

Ask Question
If you have any question, you can go to menu ‘Features -> Q&A forum-> Ask Question’.Select the desired category and post your question.
Multiple catch block in java
Final, Finally and Finalize in java
Shekhar Sharma

Shekhar Sharma

Shekhar Sharma is founder of testingpool.com. He is an automation engineer having more than 8 years of experience who loves troubleshooting in automation and finding innovative ways to solve the problems. His other leisurely activities includes playing harmonica, paintings, sketching portrait, watching movies and travelling etc.

You may also like...

1 Response

  1. August 9, 2015

    […] the previous post ,we have seen the difference between throw and throws keywords. In this post, we will see the difference between final, finally and finalize […]