• Post Reply Bookmark Topic Watch Topic
  • New Topic

performance degradation in using try/catch  RSS feed

 
Raghuveer Rawat
Ranch Hand
Posts: 102
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Is there any performance degradation in using try / catch block i.e. exception handling in our program than if we don't handle exception.
 
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
Well, your program won't exit to the operating system as quickly
 
John Smith
Ranch Hand
Posts: 2937
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Is there any performance degradation in using try / catch block i.e. exception handling in our program than if we don't handle exception.
Your code should be clear, expressive, and easy to extend and maintain. Exception handling is an important aspect of your code design, and if you are trying to optimize your code by neglecting/sacrificing exception handling, you are going in the wrong direction. As one of the founding fathers put it, "Premature optimization is the root of all evil". If there is a bottleneck in your app, it is almost certain that handling exceptions has nothing to do with it.
 
Jeroen Wenting
Ranch Hand
Posts: 5093
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Of course there will be a small impact due to the slightly larger overhead of the mechanism, but it is negligable compared to the cost of most other operations.
Maybe if you were to embed each and every single statement in your code in its own try-catch-finally block you would get a measurable impact, but normal use shouldn't matter much in the greater scheme of things.
 
Stan James
(instanceof Sidekick)
Ranch Hand
Posts: 8791
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I recall reading that try-catch doesn't impact performance ~much~ unless you actually throw exceptions. So if exceptions are "exceptional" ie rare the try-catch clauses won't hurt you enough to worry about. Does this sound real, or did I imagine it?
 
Raghuveer Rawat
Ranch Hand
Posts: 102
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
As we know in a java program if we don't put try/ catch/finally block, JVM itself takes responsibility of Exception Handling. if this is the case then whether we put try/catch/finally block or not, will it make any difference in performance.
 
John Smith
Ranch Hand
Posts: 2937
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
As we know in a java program if we don't put try/ catch/finally block, JVM itself takes responsibility of Exception Handling.
The only "responsibility" that JVM has in respect to exception handling is to keep unwinding the call stack until the first catch is encountered. If you don't handle exceptions anywhere, your program will simply exit back to operating system, as Ernest pointed out.
Again, forget about the performance implications of exception handling, instead concentrate on writing the quality code (including a sound methodology of exception handling).
If you have performance issues while running your applications, in all likelihood it has nothing to do with exception handling.
 
Raghuveer Rawat
Ranch Hand
Posts: 102
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

Again, forget about the performance implications of exception handling, instead concentrate on writing the quality code (including a sound methodology of exception handling).

I know how important is exception handling for a good quality program, I am just discussing this topic for my query.
 
Herb Schildt
Author
Ranch Hand
Posts: 253
6
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I think that Raghuveer brings up an interesting question. If I understand it correctly, he is asking whether the try/catch mechanism by itself adds runtime overhead to a program simply by its existence in the program.
The answer would seem to be Yes because at minimum the exception handler specified by the catch would have to be registered. This registration would not be required if the try/catch were not present. Of course, this is a one-time, very small expense.
BTW: The addition of a try/catch block does add size to a program. For example

This program compiles to a class file that is 387 bytes long. However, this version

Compiles to a class file that 426 bytes long.
Of course, is there a good alternative to exceptions? None that I can think of. The full integration of exceptions into Java are one of Java's main strengths.
 
Jim Yingst
Wanderer
Sheriff
Posts: 18671
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Let's not forget that empty catch blocks are EEEVIL, and that programmers who perpetrate them should be shot. (With the occasional exception for InterruptedException.) It's true that there's a nonzero effect on performance when you insert a try/catch , but it's unnoticeable in most real-world cases. Occasionally you may notice a bit of a difference in performance between

and

The latter may be a bit faster, even when no exception is ever thrown. But of course, the only really important consideration should be: if an exception is thrown, where do you want control to go? Do you want to exit the loop entirely, or do you want to move on to the next iteration?
Also worth mentioning: the overhead of actually throwing an exception is notably higher than the oeverhead for merely putting in a try/catch block. Which is part of why we avoid actually throwing them except in conditions that are, well, exceptional. And if an exception actualy is being thrown, that overhead is essentially the same no matter where we catch it - so again, best to decide where to catch it based on program logic flow, not performance.
 
Herb Schildt
Author
Ranch Hand
Posts: 253
6
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Jim is right, empty catch blocks should not be used in real code. In my preceding example, I simply left them empty as a means of obtaining the size difference caused strictly by the try/catch itself. In real code, if you catch an exception, you should handle that exception in a rational way.
Thanks again Jim for pointing this out.
 
Ilja Preuss
author
Sheriff
Posts: 14112
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Stan James:
I recall reading that try-catch doesn't impact performance ~much~ unless you actually throw exceptions. So if exceptions are "exceptional" ie rare the try-catch clauses won't hurt you enough to worry about. Does this sound real, or did I imagine it?

I remember reading something like this on the IBM website. If I remember correctly, they found out that loops over *very* big arrays could be optimized by catching the ArrayIndexOutOfBoundsException instead of testing the index on every pass.
Of course that was some time ago, so current Hotspot technology might change the result.
 
Ilja Preuss
author
Sheriff
Posts: 14112
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Herb Schildt:
Jim is right, empty catch blocks should not be used in real code.

Well, there *are* situations in which you simply "know" that the exception cannot be thrown, though Java forces you to handle it anyway. In those cases, I prefer to throw an UnreachableCodeReachedException inside the catch block...
And then there are those rare circumstances where you do know that the code *will* throw an exception, but you don't need to handle it. I prefer to write this as
catch (Exception expected) {}
 
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
I don't remember where I saw this, but I've started using

for those. I think that's the most descriptive variable name ever.
 
Ilja Preuss
author
Sheriff
Posts: 14112
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Ernest Friedman-Hill:
I don't remember where I saw this, but I've started using

for those. I think that's the most descriptive variable name ever.

Mhh, as a reader of that code, I'd rather want to know *why* you choose to ignore the exception. That you are doing it, I can already read from the empty brackets...
 
Cindy Glass
"The Hood"
Sheriff
Posts: 8521
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
[Cindy lurking - waiting until you guys are done - and then moving this to the "Performance Forum"]
 
Don Kiddick
Ranch Hand
Posts: 580
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
And then there are those rare circumstances where you do know that the code *will* throw an exception, but you don't need to handle it. I prefer to write this as

By definition this sounds bad, you are using exceptions to model expected (ie non exceptional behaviour). I guess maybe you have to do this if interfacing with 3rd party libraries ?
D.
 
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

Mhh, as a reader of that code, I'd rather want to know *why* you choose to ignore the exception. That you are doing it, I can already read from the empty brackets...

The empty brackets tell you that it's being ignored. The variable name tells you that I know it's being silently ignored. Knowing that I know I'm doing something deliberately, rather than that I'm just writing the typical newbie "try { ... } catch (Throwable t) { }" is worth something, yes?
Anyway, I think the number one area in which I use these is something like this:

This comes up in libraries that can be used either in "hosted" code like Applets or RMI code, or else in plain-old unrestricted desktop apps. The library doesn't necessarily know how it's being used, so it has to adapt.
 
Ilja Preuss
author
Sheriff
Posts: 14112
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Don Kiddick:

By definition this sounds bad, you are using exceptions to model expected (ie non exceptional behaviour). I guess maybe you have to do this if interfacing with 3rd party libraries ?

Well, the most popular example is the JUnit idiom for testing that an Exception gets thrown:

Currently, not other example comes to mind...
 
Don Kiddick
Ranch Hand
Posts: 580
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
hmmm... yes, the exception that proves the rule !
 
Jim Yingst
Wanderer
Sheriff
Posts: 18671
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Good points, there are other cases where ignoring an exception is the correct thing to do. If the programmer is sure of what they're doing. I just hate to see it presented as the default, ever, since too many programmers (esp beginners) do it when they simply aren't sure what else to do, and this is almost certainly wrong.
In those cases, I prefer to throw an UnreachableCodeReachedException inside the catch block...
Sounds good, except I can't find such an exception anywhere. Does it have another name, or were you just making something up? How about

[Ilja]: Mhh, as a reader of that code, I'd rather want to know *why* you choose to ignore the exception. That you are doing it, I can already read from the empty brackets...
[Ernest]: The empty brackets tell you that it's being ignored. The variable name tells you that I know it's being silently ignored. Knowing that I know I'm doing something deliberately, rather than that I'm just writing the typical newbie "try { ... } catch (Throwable t) { }" is worth something, yes?

Something, yes, but I do agree with Ilja that I'd usually like to know why, too, unless it's really obvious. For JUnit testing we do that sort of thing often enough that anyone looking at the test code will have to figure it out soon enough; I wouldn't expect a comment each time it happens. Most other cases I'd try to comment though:

YMMV and all that...
[ October 02, 2003: Message edited by: Jim Yingst ]
 
Cindy Glass
"The Hood"
Sheriff
Posts: 8521
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Moved to Performance Forum.
 
Jim Yingst
Wanderer
Sheriff
Posts: 18671
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Oh sure, Cindy - wait until we're not even talking about performance anymore.
 
Ilja Preuss
author
Sheriff
Posts: 14112
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Ernest Friedman-Hill:

This comes up in libraries that can be used either in "hosted" code like Applets or RMI code, or else in plain-old unrestricted desktop apps. The library doesn't necessarily know how it's being used, so it has to adapt.

Oh ok, - that I wouldn't have a problem with.
 
Ilja Preuss
author
Sheriff
Posts: 14112
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Jim Yingst:
In those cases, I prefer to throw an UnreachableCodeReachedException inside the catch block...
Sounds good, except I can't find such an exception anywhere. Does it have another name, or were you just making something up?

That's a custom exception we introduced at work recently, exactly for this purpose.

How about


Looks good, except that I don't like to
- put information into comments I could also have been put into the code itself, and
- repeat myself
That's why something along the lines of
throw new ShouldNeverHappenException("and perhaps explain why");
looks more intriguing to me.
 
Jim Yingst
Wanderer
Sheriff
Posts: 18671
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Well there's always

Actually I'd say that

by itself implies "unreachable code", though perhaps the idiom is not well-known enough, so an extra comment or string is justified. And in fact "unreachable" is potentially confusing terminology; if the code were really unreachable as the JLS defines the term, the compiler wouldn't be letting us put any code there in the first place.
Hmmmm - I suppose the choice of assert false vs. UnreachableCodeException depends on who your target audience (other programmers) is. UnreachableCodeException will be unfamiliar to programmers who haven't seen your company's custom classes before, but you can reasonably expect them to learn it pretty darn quick as long as they have access you your source. (I.e. it's not so great in a random JavaRanch conversation). While assert false is standard, but not quite as readable (unless/until the idiom is more widely used), and for anyone not using 1.4+ of course it doesn't work (but those luddites will die off eventually, right?) and or course assert only works if you've got assertions enabled, for better or worse. So I could go either way here depending on context.
[ October 04, 2003: Message edited by: Jim Yingst ]
 
David Weitzman
Ranch Hand
Posts: 1365
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thoeretically, merely opening and closing a try-catch block shouldn't *need* to add any overhead. Given that a RuntimeException can be thrown in many circumstances, the JVM probably inserts lots of exceptional circumstance continuation code anyway. However I believe a previous dicussion of this subject at JavaRanch led to the belief that IBM's virtual machine actually *does* have degraded performance within a try-catch block, whereas there was no evidence to believe that Sun's has degraded performance. (And just to avoid any bias, it could be that Sun's always has degraded performance while IBM just optimizes better )
 
Jim Yingst
Wanderer
Sheriff
Posts: 18671
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
At JavaOne 2003 Cliff Click gave a nice talk on Perfromance Myths Exposed. There's some relevant data for several modern JVMs. Cost of try/catch is covered under Myth 3: try/catch blocks are free (or not). Basically, they're free, except in tight inner loops. IBM fares poorer on this particular test, but there's a nonzero cost for Sun as well. On other tests (not regarding try/catch), IBM did better, so the overall results were mixed.
Here's a test showing the difference between a try/catch inside a loop and a try/catch outside.

My output using JDK 1.4.2 on Windows 2000:

(I repeated the tests as a simple way to see if startup costs were significant - they weren't, for n = 100000000 anyway.)
Note that in order to see a measurable difference, I made sure that the loop was very simple - the only thing it does is sum += i. Most real-world applictaions will do something a little more complex, which will mean the try/catch effect will be less significant.
Another important point of Dr.Click's talk was that most perfomance advice ages poorly. Most of the myths he discussed were true at some point in the past, but JVM technology keeps advancing, and what was once good advice for a particular JVM becomes irrelevant or just plain wrong. IBM' poor showing for the try/catch performance was true in summer of 2003; I wouldn't be surprised if that's fixed soon, if not already.
 
Don't get me started about those stupid light bulbs.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!