M.Mac
M.Mac

Reputation: 739

Java, does overusing try/catch result in performance issues?

i thought about the fact, that using try and catch is useful to prevent crashes if there are mistakes, but i was curious if there is any impact at the performance if i overuse the try and catch block.

To resume: Is there any impact at the performance if i use try and catch(nearly) everywhere?

Upvotes: 1

Views: 710

Answers (2)

biziclop
biziclop

Reputation: 49754

Exception throwing/handling does come with a slight performance penalty (the exact amount varies greatly by the exact scenario), but performance shouldn't be your first consideration.

  1. Correctness: First of all, make sure that your code does what it needs to do. Don't treat normal use cases as exceptional, for example if a user types in an incorrect value in a field, that's nothing special, no need to throw exceptions for that. But if something is genuinely exceptional (like you can't connect to the database), and you can't deal with it at the point it occurs, throw an exception. And if the exception comes from "below", from a JDK class or a third party library, you have no other option than to handle it.
  2. Readability. Constantly catching and re-throwing exceptions can make your code near impossible to follow, debug or maintain. The same goes for swallowing exceptions without a trace. What you should aim for instead is a consistent strategy for handling exceptions. Basically you should only handle exceptions on the level where you can do something about them.
  3. Performance. This should be your last port of call, once you get the first two sorted. It is unlikely that you'll ever be in a place where your code is correct and readable, and still exception handling is the main bottleneck of your application, but if you do get there, you can try returning error codes rather than throwing exceptions, or completely restructuring your code to avoid them.

Upvotes: 2

Armin Braun
Armin Braun

Reputation: 3683

I think the main hit to performance you are going to see (assuming the code in question is executed at a very high frequency) will be from garbage collection.

One trivial example (this you do actually see in production code every now and then ...) would be having password verification logic like:

if (!password.equals(correctPassword)) {
   throw new IncorrectPasswordException();
}

and then ...

catch (final IncorrectPasswordException ex) {
   //some output or so
}

... instead of simply never throwing anything and just handling this via conditionals. You will eventually have to clean up all those IncorrectPasswordException from memory.

In this case overusing exceptions actually will become pretty costly by turning simple evaluations into object instantiations that cost you memory and even more importantly eventually cost you precious CPU cycles for reclaiming that memory via garbage collection.

Upvotes: 2

Related Questions