How to Throw exception in java

Exceptions in java can be thrown using the “throw” keyword.
The throw statements requires a object to throw. This object needs to be a throwable object.

Syntax:

In java we can throw both checked and unchecked exceptions. Lets see some examples on throwing both of these types of exceptions and the differences in throwing these exceptions.

How to throw exception in java – Unchecked Exceptions

Look at the below example, we check if list is null and then throw NullPointerException.
In this case NullPointerException is unchecked exception, hence we do not need to mention this in the method signature.

How to throw exception in java – Checked Exceptions

As we saw in the above example, when throwing an unchecked exception its not required to specify in the method signature about the exception that will be possibly thrown from the method.

But when we deal with checked exception we need to use throws keyword to specify the exception that may be thrown from the method.
Lets take the above example and change the exception thrown from unchecked (NullPointerException) to checked (IOException)
You will see that we need to mention the thrown exceptions in method signature, else code gives compilation errors.

It's only fair to share...Share on FacebookShare on Google+Tweet about this on TwitterShare on LinkedIn