How to check what type of exception was thrown in Java?

How to determine what 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 detected?

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

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

+15
source share
3 answers

If you can, always use separate catch blocks for individual types of exceptions, otherwise there is no excuse:

 } catch (NotAnInt e) { // handle NotAnInt } catch (ParseError e) { // handle ParseError } 

... if you do not need to share some general steps and not use additional methods for brevity:

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

however, common steps can also be extracted into methods to avoid the if - else block:

 } catch (NotAnInt e) { inCommon1(e); // handle NotAnInt inCommon2(e); } catch (ParseError e) { inCommon1(e); // handle ParseError inCommon2(e); } private void inCommon1(e) { // several steps // in common to // both cases } private void inCommon2(e) { // potentially several more // steps in common // to both cases } 
+32
source

Use multiple catch blocks, one for each exception:

 try { int x = doSomething(); } catch (NotAnInt e) { // print something } catch (ParseError e){ // print something else } 
+11
source

If multiple throws occur in the same catch() to recognize which exception, you can use the instanceof operator.

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

Try this code: -

  catch (Exception e) { if(e instanceof NotAnInt){ // Your Logic. } else if if(e instanceof ParseError){ //Your Logic. } } 
+2
source

Source: https://habr.com/ru/post/1208288/


All Articles