Lesson 6 | Multiple Catch Blocks in Java |
Objective | Handling more than one type of Exception. |
Multiple Catch Blocks in Java
Handling more than one type of Exception.
Describe how to handle more than one type of exception.
If you want to handle more than one type of exception, you can define multiple catch blocks. For example, you could write:
(In the code below, NumberFormatException is a RuntimeException.)
try {
// try something here
} catch (NumberFormatException e) {
// handle number format exceptions here
} catch (IOException e) {
// handle IOexceptions here
}
We said that one way to handle an exception was to rethrow it. Here's an example. Let us say your method converts a string into a number.
Here's how the constructor for Integer that takes a string is declared:
public Integer(String s) throws NumberFormatException
The documentation notes that this constructor throws the indicated exception if s does not contain a valid number.
Therefore, one possible way to proceed is to place the call to the constructor inside a try block and handle the exception.
Yet another way to proceed is to indicate that your own code might generate an exception:
Integer myIntegerCreator(String s) throws NumberFormatException {
return new Integer(s);
}
Catching Exceptions - Exercise
Catching Java Exceptions Quiz