Win a copy of Cross-Platform Desktop Applications: Using Node, Electron, and NW.js this week in the JavaScript forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

exception handling  RSS feed

 
Inesh Hettiarachchi
Greenhorn
Posts: 25
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
hi
does try catch blocks effect the performance of a java code
inesh
 
Ernest Friedman-Hill
author and iconoclast
Sheriff
Posts: 24217
38
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The try and catch blocks themselves have virtually no effect on performance, as long as no exceptions are actually thrown. But throwing an exception is itself a very slow operation. Since normal operation of your program should not include any exceptions being thrown, this is generally not an issue.
 
Inesh Hettiarachchi
Greenhorn
Posts: 25
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
thanks Ernest for the reply
inesh
 
Peter Chase
Ranch Hand
Posts: 1970
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Ernest Friedman-Hill:
throwing an exception is itself a very slow operation


Do you have any figures to show how slow it is?
 
Ernest Friedman-Hill
author and iconoclast
Sheriff
Posts: 24217
38
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Peter Chase:


Do you have any figures to show how slow it is?


It's intuitively pretty expensive because it involves constructing an Exception, which involves constructing a StackTraceElement[], which can be quite a few objects -- each of them involving a native call or two, which is itself expensive.

I just went and looked in Jack Shirazi's "Java Performance Tuning", second edition. He's got a benchmark on pages 174-175 that shows that in JDK 1.4, anyway, doing a cast that throws a ClassCastException is fully 100 times slower then just testing with instanceof and branching.
 
Isuru Sampath
Ranch Hand
Posts: 57
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Ok, it is slow to thorw exceptions, but is there any alternative for this?
 
Ajith Kallambella
Sheriff
Posts: 5782
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Preventing exception scenarios is one strategy - good programming habits such as null checking object references before accessing a member/method.

Unfortunately, not everything can be avoided. For example, RuntimeException-s are hard to predict. So are IOException categories.
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!