Difference Between throw And throws in Java

In Java five keywords are used for exception handling namely – try, catch, finally, throw and throws. Out of these five, throw and throws keywords sound quite similar causing confusion thus the question what are the differences between throw and throws in Java exception handling.

Throw vs Throws in java

1- throws clause is used to declare an exception with in the method signature where as throw is used with in the code to actually throw an exception.

Exception declaration with in the method signature using throws

Throwing exception using throw keyword

2- With throws clause multiple exceptions can be declared as a comma separated list. Where as throw can throw only a single instance of exception.

Declaring multiple exception with throws clause

3- With throws clause you can declare all the exceptions that may be thrown by your method code. You are not actually throwing an exception, just declaring them so the caller method can provide exception handling for the declared exceptions.
With throw you are actually throwing an exception that looks for the nearest catch block with the matching exception type.

4- With throw keyword you use an instance of the Throwable class or any of its sub-class, you don’t use the exception class itself.
With throws, while declaring exceptions you use the name of the exception classes itself.

With throw

or you create an exception class object and throw it-

With throws –

Class name (IOException) itself is given with the throws clause.

5- There is a restriction with throws clause that it has to be used with the method signature where as throw statement has to be part of the code where it may come anywhere inside the method, throw statement can be used with in a static block too.

Using throw with static block

That’s all for the topic Difference Between throw And throws in Java. If something is missing or you have something to share about the topic please write a comment.


You may also like

One Comment

  1. Pingback: How to Use LZO Compression in Hadoop - KnpCode

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.