Android does not support Java v7 +, so should I use multiple catches or one catch with instanceof checks?

I have 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 can 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 does not yet support Java 7+, I cannot use the above. What are the risks in the following:

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 do not have enough experience or knowledge, so I do not know the risks. Are there any unexpected results? Are there any performance changes at runtime and / or at compile time? and etc.

If there are no risks, high performance changes or unexpected results, then why not use instanceof for one catch? If there is any risk, I think it's better to use a few catches that are better supported by both Android / Java itself and compilation behind the scenes.

+4
1

Eclipse Java 7 Window > Preferences > Java > Compiler ( "Windows" Apple OS X IIRC).

, API- 19+ SDK (Project > Properties > Android ). , Eclipse/ADT , .

SDK 19+, Java 7, SomeException | SomeOtherException | AndYetAnotherException.

+7

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


All Articles