I know since Java 7 you can use multi-catch
but I wonder if the order of exceptions in it matters like in previous versions of java? E.g I put in Exception and then SQLException
and IOException
?
try {
// execute code that may throw 1 of the 3 exceptions below.
} catch(Exception | SQLException | IOException e) {
logger.log(e);
}
Or should I do it this way ?
try {
// execute code that may throw 1 of the 3 exceptions below.
} catch(SQLException | IOException e) {
logger.log(e);
} catch(Exception e) {
logger.severe(e);
}
There's no point in a single catch block for catch(Exception | SQLException | IOException e)
since Exception
already covers its sub-classes IOException
and SQLException
.
Therefore catch(Exception e)
would be enough if you wish the same handling for all of those exception types.
If you want different handling for the more general Exception
, your second code snippet makes sense, and here the order of the two catch blocks matters, since you must catch the more specific exception types first.
Yes Order is important, it is from Child to Parent.
Refer this for more such.
The exception variable is implicitly final, therefore we cannot assign the variable to different value within the catch block. For example, the following code snippet will give a compile error
} catch (IOException | SQLException ex) {
ex = new SQLException();
}
The compiler will throw this error: multi-catch parameter ex may not be assigned
It is not allowed to specify two or more exceptions of a same hierarchy in the multi-catch statement. For example, the following code snippet will give a compile error because the FileNotFoundException is a subtype of the IOException
} catch (FileNotFoundException | IOException ex) {
LOGGER.log(ex);
}
The compiler will throw this error (no matter the order is): Alternatives in a multi-catch statement cannot be related by subclassing
The Exception class is the supertype of all exceptions, thus we also cannot write
} catch (IOException | Exception ex) {
LOGGER.log(ex);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With