Handling multiple exceptions in one exception handler block

A

Adisht

Hi all,
I can anyone send me an example of how to catch 2 exceptions but handle
them together ?
Thanks,
Adi
 
I

Ingo R. Homann

Hi,
Hi all,
I can anyone send me an example of how to catch 2 exceptions but handle
them together ?
Thanks,
Adi

Unfortunatly, (if the two exceptions do not have a supertype which the
other exceptions do not have) this is not possible. You can only extract
your code to a method:

try {
...
} catch(Exception1 e1) {
error(e1);
} catch(Excpetion2 e2) {
error(e2);
}

(Another possibility would be to catch the general class "Exception" and
to do an instanceof-check, but this is not a good idea IMHO.)

Ciao,
Ingo
 
C

Chris Brat

Adisht said:
Hi all,
I can anyone send me an example of how to catch 2 exceptions but handle
them together ?
Thanks,
Adi

hi,

I had to catch two exceptions, which did not extend the same class, and
log the details of these exceptions. But I did not want to catch all
Exceptions or Throwables that could possibly occur so I did the
following:

1.) Wrapped the code and caught the possible exceptions I want handled

try{
// logic that could throw exception

} catch (Exception1 e1){
handleExceptionWithCommonCode(e1);
} catch (Exception2 e2){
handleExceptionWithCommonCode(e2);
}


2.) Then wrote a private method to handle these exceptions

private void handleExceptionWithCommonCode(Exception e){
// process the exception i.e. log it
}


Am also curious to see if anyone has a neater solution.

Chris
 
L

Luc The Perverse

Ingo R. Homann said:
Hi,


Unfortunatly, (if the two exceptions do not have a supertype which the
other exceptions do not have) this is not possible. You can only extract
your code to a method:

You could say that having a supertype is the way to do this :) This would
of course suggest that you are the one generating and throwing the
exceptions.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,769
Messages
2,569,582
Members
45,057
Latest member
KetoBeezACVGummies

Latest Threads

Top