Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android doesn't support Java v7+, so should I use multiple catches or one catch with instanceof checks?

I've got the following situation:

try{
    // Do some things that can cause the exceptions
}
catch(SomeException ex){
    doSomething();
}
catch(SomeOtherException ex){
    doSomething();
}
catch(AndYetAnotherException ex){
    doSomething();
}
catch(Exception ex){
    // Do something else
}

In Java v7+ I could change this to:

try{
    // Do some things that can cause the exceptions
}
catch(SomeException | SomeOtherException | AndYetAnotherException ex){
    doSomething();
}
catch(Exception ex){
    // Do something else
}

Since Android doesn't support Java 7+ yet, I can't use the above. What are the risks of doing the following instead:

try{
    // Do some things that can cause the exceptions
}
catch(Exception ex){
    if(ex instanceof SomeException || ex instanceof SomeOtherException || ex instanceof AndYetAnotherException){
        doSomething();
    }
    else{
        // Do something else
    }
}

I don't have enough experience or knowledge of instanceof, so I don't know the risks. Are there unexpected results that might occur? Are there performance changes during run-time and/or during compilation? etc.

If there aren't any risks, high performance changes or unexpected results, then why not use the instanceof for a single catch? If there are however any risk whatsoever, I guess it's better to use multiple catches which is supported better by both Android/Java itself and the compilation behind the scenes.

like image 659
Kevin Cruijssen Avatar asked Mar 19 '23 03:03

Kevin Cruijssen


1 Answers

You can update Eclipse to use Java 7 syntax checking, via Window > Preferences > Java > Compiler from the main menu (replacing "Windows" with the Apple menu on OS X IIRC).

However, note that you need to have API Level 19+ as your build SDK (Project > Properties > Android from the main menu). If it is lower, Eclipse/ADT will be unhappy, expressing that unhappiness in the form of lots of red pixels.

But, if you change the compiler setting and have your build SDK set to 19+, this does enable Java 7 syntax, including your SomeException | SomeOtherException | AndYetAnotherException syntax.

like image 174
CommonsWare Avatar answered Apr 25 '23 07:04

CommonsWare