1

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(); } 

1 Answer 1

3

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
Sign up to request clarification or add additional context in comments.

5 Comments

Great answer as always! Thanks Jon!
At least the catch block wasn't just plain empty - I've seen that in code way too many times ...
Hypothetical situation @BertF, example code for the sake of brevity
@Styler - yeah, I figured - I wasn't actually commenting on your code. Jon's comment about "the right way of handling" just spurred me to remember how many times I've reviewed junior devs code and found empty catch blocks (Unfortunately, it wasn't "sample code for brevity").
It would be fun to edit the code and put the comment in the catch "//Sample code for brevity", maybe it will end up in some poor souls project via a copy/paster trying to handle their exceptions ;)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.