In Java, you can use multiple catch
blocks.
It doesn't necessarily means you have to.
It depends on the code your have in the try
block, and how many checked Exception
s it may potentially throw (or even unchecked Exception
s if you really want to catch that, typically you don't and you don't have to).
One bad practice is to use a single handler for general Exception
(or worse, Throwable
, which would also catch RuntimeException
s and Error
s):
try {
// stuff that throws multiple exceptions
}
// bad
catch (Exception e) {
// TODO
}
The good practice is to catch all potentially thrown checked Exception
s.
If some of them are related in terms of inheritance, always catch the child classes first (i.e. the more specific Exception
s), lest your code won't compile:
try {
// stuff that throws FileNotFoundException AND IOException
}
// good: FileNotFoundException is a child class of IOException - both checked
catch (FileNotFoundException fnfe) {
// TODO
}
catch (IOException ioe) {
// TODO
}
Also take a look at Java 7's multi-catch blocks, where unrelated Exception
s can be caught all at once with a |
separator between each Exception
type:
try (optionally with resources) {
// stuff that throws FileNotFoundException and MyOwnCheckedException
}
// below exceptions are unrelated
catch (FileNotFoundException | MyOwnCheckedException e) {
// TODO
}
Note
In this example you linked to, the first code snippet below Putting it all together may arguably be considered as sub-optimal: it does catch the potentially thrown Exception
s, but one of them is an IndexOutOfBoundsException
, which is a RuntimeException
(unchecked) and should not be handled in theory.
Instead, the SIZE
variable (or likely constant) should be replaced by a reference to the size of the List
being iterated, i.e. list.size()
, in order to prevent IndexOutOfBoundsException
from being thrown.
I guess in this case it's just to provide an example though.