Use a method for generic code.
try { // do something... } catch (ExceptionA e) { // actions for ExceptionA doCommon(parameters); } catch (ExceptionB e) { // actions for ExceptionA doCommon(parameters); } ..... void doCommon( parameters ) { // actions for ExceptionA & ExceptionB }
This will work for most things.
Although there are some exceptions, such as return . To do this, you can return doCommon so that the caller should return or not, and use it as:
catch (ExceptionA e) { // actions for ExceptionA if ( doCommon(parameters) ) return; } catch (ExceptionB e) { // actions for ExceptionA if ( doCommon(parameters) ) return; }
The native Java solution does not exist. JLS indicates (my attention):
14.20.1. Doing try-catch
A try statement without a finally block is executed by first executing a try block. Then there is a choice:
If the execution of the try block completes normally, the action is executed, and the try statement completes normally.
If the execution of the try block terminates abruptly due to a throw of the value V, then there is a choice:
If the run-time type V is an assignment compatible with (clause 5.2) that captures the exception class of any catch clause in the try statement, then the first (left-most) catch clause is selected . The value V is assigned to the parameter of the selected catch clause, and the block of this catch clause is executed, and then there is a choice:
If this block completes normally, then the try statement completes in normal mode.
If for any reason this block terminates abruptly, try the Statement terminates abruptly for the same reason.
If the run-time type of V is not an assignment compatible with the catching exception class of any catch clause in the try statement, then the try statement terminates abruptly due to a throw of V.
Thus, only the first blocking catch block is executed. It is not possible to execute two catch blocks for the same try statement.