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:
1 |
throw throwableObject |
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.
1 2 3 4 5 6 7 8 9 10 11 12 13 |
public String convertListToString(List<String> list) { /* * Check if list is null and then throw NullPointerException */ if (list == null) { throw new NullPointerException(); } String convertedString = ""; for (String str : list) { convertedString = convertedString + str; } return convertedString; } |
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.
1 2 3 4 5 6 7 8 9 10 11 12 13 |
public String convertListToString(List<String> list) throws IOException { /* * Check if list is null and then throw IOException */ if (list == null) { throw new IOException(); } String convertedString = ""; for (String str : list) { convertedString = convertedString + str; } return convertedString; } |