52

How can I determine which type of exception was caught, if an operation catches multiple exceptions?

This example should make more sense:

try {
  int x = doSomething();
} catch (NotAnInt | ParseError e) {
  if (/* thrown error is NotAnInt */) {    // line 5
    // printSomething
  } else {
    // print something else
  }
}

On line 5, how can I check which exception was caught?

I tried if (e.equals(NotAnInt.class)) {..} but no luck.

NOTE: NotAnInt and ParseError are classes in my project that extend Exception.

jww
  • 97,681
  • 90
  • 411
  • 885
jean
  • 973
  • 1
  • 11
  • 23

4 Answers4

72

If you can, always use separate catch blocks for individual exception types, there's no excuse to do otherwise:

} catch (NotAnInt e) {
    // handling for NotAnInt
} catch (ParseError e) {
    // handling for ParseError
}

...unless you need to share some steps in common and want to avoid additional methods for reasons of conciseness:

} catch (NotAnInt | ParseError e) {
    // a step or two in common to both cases
    if (e instanceof NotAnInt) {
        // handling for NotAnInt
    } else  {
        // handling for ParseError
    }
    // potentially another step or two in common to both cases
}

however the steps in common could also be extracted to methods to avoid that if-else block:

} catch (NotAnInt e) {
    inCommon1(e);
    // handling for NotAnInt
    inCommon2(e);
} catch (ParseError e) {
    inCommon1(e);
    // handling for ParseError
    inCommon2(e);
}

private void inCommon1(e) {
    // several steps
    // common to
    // both cases
}
private void inCommon2(e) {
    // several steps
    // common to
    // both cases
}
Erik Kaplun
  • 37,128
  • 15
  • 99
  • 111
  • 1
    In which case can't you put multiple catch blocks ? Just curious. – Chargnn Jun 15 '19 at 18:02
  • @Chargnn I was wondering the same. Maybe if the `catch` block was calling some `onException(Exception e)` callback? The other answer is better, IMHO. – Matthieu Jun 15 '19 at 18:16
  • 1
    sorry, I made a detrimental edit to the post recently, which I have reverted now (and further improved upon). – Erik Kaplun Jun 16 '19 at 06:30
25

If Multiple throws are happening in a single catch() then to recognize which Exception , you could use instanceof operator.

The java instanceof operator is used to test whether the object is an instance of the specified type (class or subclass or interface).

Try this code :-

        catch (Exception e) {
            if(e instanceof NotAnInt){

            // Your Logic.

            } else if  if(e instanceof ParseError){                

             //Your Logic.
            }
      }
anoopknr
  • 3,177
  • 2
  • 23
  • 33
  • 2
    And how is that different from what was written in the accepted answer 4 years befire you wrote your answer? – GhostCat Jun 15 '19 at 17:45
  • @GhostCat thank you! There are so many copy-paste posts like these cluttering such questions... – Matthieu Jun 15 '19 at 18:17
  • 3
    This answer is different from the accepted (and helpful) because it focuses on one solution, which was tucked away in the example and not mentioned or explained in the answer text. Separate catch blocks did not work for my problem because I was looking at the root cause of a single exception type, so I skimmed those answers. – Noumenon Jun 27 '19 at 16:40
  • 1
    This, quite precisely, what I was looking for! I have a multi-catch which, for one exception type only, I want to deviate from the normal behaviour. – Dave Apr 28 '21 at 16:21
16

Use multiple catch blocks, one for each exception:

try {
   int x = doSomething();
}
catch (NotAnInt e) {
    // print something
}
catch (ParseError e){
    // print something else
}
Worldcrafter
  • 35
  • 1
  • 6
DavidGSola
  • 697
  • 5
  • 17
5

If anyone didn't know what type of exception was thrown in the method e.g a method with a lot of possibilities like this one :

public void onError(Throwable e) {

}

You can get the exception class by

       Log.e("Class Name", e.getClass().getSimpleName());

In my case it was UnknownHostException

then use instanseof as mentioned in the previous answers to take some actions

public void onError(Throwable e) {
       Log.e("Class Name", e.getClass().getSimpleName());

       if (e instanceof UnknownHostException)
            Toast.makeText(context , "Couldn't reach the server", Toast.LENGTH_LONG).show();
       else 
          // do another thing
}
Mohammad
  • 1,185
  • 1
  • 14
  • 26