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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With