Use a method for the common 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
}
That will work for most things.
Though there are some exceptions like return
. For that you can have doCommon
return wether the caller has to 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;
}
A "native Java" solution does not exist. JLS specifies (emphasis mine) :
14.20.1. Execution of try-catch
A try statement without a finally block is executed by first executing
the try block. Then there is a choice:
If execution of the try block completes normally, then no further
action is taken and the try statement completes normally.
If execution of the try block completes abruptly because of a throw of
a value V, then there is a choice:
If the run-time type of V is assignment compatible with (§5.2) a
catchable exception class of any catch clause of the try statement,
then the first (leftmost) such catch clause is selected. The value V
is assigned to the parameter of the selected catch clause, and the
Block of that catch clause is executed, and then there is a choice:
If that block completes normally, then the try statement completes
normally.
If that block completes abruptly for any reason, then the try
statement completes abruptly for the same reason.
If the run-time type of V is not assignment compatible with a
catchable exception class of any catch clause of the try statement,
then the try statement completes abruptly because of a throw of the
value V.
So only the first catch block which applies is executed. There is no way to execute two catch blocks for the same try statement.
handleExceptionA
,handleExceptionB
andhandleExceptionAandB
so he cann coll the methods in catch block.