Difference between Throw and Throws in Java

In this tutorial you will learn about difference between throw and throws keywords in java with example.

When we run a java program which contains errors, programmers should handle errors by exception handling (using try, catch and finally blocks) or avoid (throw) it. Otherwise JVM will give error which causes the termination of the running program and loss of data that has been processed till that line of the program.

Throw and Throws are two keywords used in java syntax related to exception feature of Java and used when programmer wants to throw the errors without handling.

Now let’s see the differences between the throw and throws clause.

Difference between Throw and Throws in Java

Throw Throws
1. throw clause or keyword is used in Java to throw an exception explicitly. throws clause or keyword is used in Java to declare an exception.
2. We can use throw in any part of code. We must use throws only at method declaration.
3. At a time we can throw only one exception using throw keyword.

Ex: throw new IOException(“File not found”);

At a time we can declare multiple exceptions using throws keyword.

Ex: public void func() throws IOException, SQLException { //some code}

4. throw is followed by instance only. throws is followed by class name.
5. We cannot propagated checked exception using throw only. We can propagated checked exception using throws.

Throw Example

Example to explain the use of throw clause for throwing the NullpointerException.

Output

Inside demo()

Java.lang.NullPointerException : Exception data

In this program, we are using throw clause to throw NullPointerException class object. Then it is caught and its details are displayed in catch block.

Throws Example

Example to explain the use of throws clause.

Output

Programmer

Name : Programmer

In this program we are using throws clause to throw out an exception without handling it from a method.

Comment below if you found any mistake or have queries regarding above tutorial for difference between throw and throws in Java.

Leave a Reply

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