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.)
We said that one way to handle an exception was to rethrow it. Here's an example.
Let's say your method converts a string into a number.
Here's how the constructor for Integer that takes a string is declared:
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:
This exercise asks you to modify code to handle a couple of exceptions that could be thrown when using this program.
Catching Exceptions - Exercise
When you finish the exercise, return here to take a quiz on exceptions.
Catching Java Exceptions Quiz