Cost of having try-catch statements?

Andrew Pinski pinskia@physics.uc.edu
Tue Aug 10 17:08:00 GMT 2004


On Aug 10, 2004, at 9:57 AM, Harald Niesche wrote:

> Andrew Haley wrote:
>
>> Martin Egholm Nielsen writes:
>>  > >  > I was wondering: Is there any significant cost in having 
>> "unused"  > >  > try-catches in my code?
>>  > >  > That is, I have a method that 99.99% of the times invoked 
>> never throws a  > >  > given exception. However, in case it does, I 
>> need to log it...
>>  > > The only cost is the unwinder tables, (which are not read into 
>> memory
>>  > > unless your exception is thrown) and the handler itself, which 
>> may
>>  > > cause some instruction cache presure.
>>  > So practically no overhead?
>> That's the idea.  Really, if there is any significant overhead for an
>> unused handler that would be a bug.
>
> Being curious, I tried a micro benchmark (Main.java, attached).
>
> The code just calls a method on an instance of class Main that then 
> proceeds to call another method (that will never throw an exception, 
> it simply increments a member to be not completely empty). In the 
> first case there is nothing happening besides the second function 
> being called, in the second case I have wrapped a try/catch around the 
> call.
>
> The time given is how long it takes to execute 10,000,000 calls in a 
> for loop. Each test is repeated twice before any measurement takes 
> place.


Oh on windows this is because gcj (and g++) uses setjmp/longjmp to 
emulate exceptions
so the overhead will be much higher than say on Linux or Mac OS X.

-- Pinski



More information about the Java mailing list