Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

order in multi-catch exception handler

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);
}
like image 514
Dodi Avatar asked Jan 08 '23 23:01

Dodi


2 Answers

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.

like image 77
Eran Avatar answered Jan 18 '23 14:01

Eran


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);

}
like image 40
Ankur Singhal Avatar answered Jan 18 '23 14:01

Ankur Singhal