Win a copy of Head First Agile this week in the Agile forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

throws Vs try..catch  RSS feed

 
kri shan
Ranch Hand
Posts: 1489
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Which one is performance wise beter method level throws or try..catch ??
 
Heonkoo Lee
Ranch Hand
Posts: 85
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Throwing an exception to JVM makes the virtual machine busy poping up the exception stack until it finds the root cause. So, it may slow down the program more than catching an exact exception. It is my thinking.
 
David Harkness
Ranch Hand
Posts: 1646
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Regardless of performance, they are fundamentally different beasts. If you let an exception propagate from your method, it goes to the caller. If you catch it, you can handle it.

It's like asking "Which is more performant, returning a null or using a for loop?" You're comparing apples and oranges that can't be used in place of the other.
 
Heonkoo Lee
Ranch Hand
Posts: 85
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
That makes it clear. I'm learning a lot from JavaRanch.

Thank you.
 
David Harkness
Ranch Hand
Posts: 1646
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Heonkoo, I believe that your point was indeed valid. There is a small speed price to be paid when setting up a try-catch block, however small it may be. And it is possible that propagating the exception up the call chain might be slower than returning normally up that chain.

My point was only that the decision to propagate or catch should be based solely on the needs of the methods involved, not on performance. Performance concerns should only come into play when considering two equivalent algorithms, for example deciding between a HashMap or TreeMap.

Correctness first, performance last. And preferably only after profiling to determine that there is in fact a problem and where it lies.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!