简体   繁体   中英

Non throwable code inside of a try/catch performance java

Will there be any negative performance implications on the following code due to methods that do not throw exceptions being inside of a try block?

String user;
try {
    user = SomeHelper.getUserName();    //Does not throw anything explicitly

    if (SomeHelper.isSomething(user)) { //Does not throw anything explicitly
        user.doSomeSafeThing(this);     //Does not throw anything explicitly
    }
    else {
        user.doOtherSafeThing(this);    //Does not throw anything explicitly
    }

    SomeOtherHelper.methodThatCanBlow(User.getCredentials(context)); //This will throw exception
} catch (Exception e) {
    e.printStackTrace();
}

I believe that the compiler will not refactor any of this code due to the fact that any of those methods could potentially throw a NullPointerException, or another RuntimeException and actually be caught in the catch block.

So I beg to ask the question, would the following code be more efficient?

String user;

user = SomeHelper.getUserName();    //Does not throw anything explicitly

if (SomeHelper.isSomething(user)) { //Does not throw anything explicitly
    user.doSomeSafeThing(this);     //Does not throw anything explicitly
}
else {
    user.doOtherSafeThing(this);    //Does not throw anything explicitly
}
try {
    SomeOtherHelper.methodThatCanBlow(User.getCredentials(context)); //This will throw exception
} catch (Exception e) {
    e.printStackTrace();
}

Will there be any negative performance implications on the following code due to methods that do not throw exceptions being inside of a try block?

No, it won't have any performance implications, but:

  • I would generally put minimal code in a try block anyway
  • I would try to avoid catching Exception , instead catching specific exceptions
  • Just printing a stack trace is very rarely the right way of "handling" and exception that you catch. Usually you want to abort the whole operation, whatever that consists of

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM