|
||
|
|
Multiple catch blocks |
|
|
Objective
|
Handle 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: |
|
|
active directory, oracle, pmp
soa testing, php, surveillance, QOS in VoIP
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's 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);
}
|
||
|
|
||
|
Exercise: Catching exceptions
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 |
||
|
|
||