Overhead associated with Exception vs Throwable in Java

WhyNotHugo picture WhyNotHugo · Jan 25, 2010 · Viewed 53.7k times · Source

I know

throw new Exception();

has a pretty large overhead, since it creates a full stackTrace, etc.
Does

throw new Throwable();

present the same problem? Is this behaviour inherited, or does throwing a Throwable has a smaller (o no) overhead?

EDIT
From an analyst point of view, a user inserting wrong password is an exception to the normal execution order of a program. So if I have:

public Session newSession() {  
  validate_user_and_password();   
}

throwing a UserNotValidException would sound correct from an analysts point of view.
Returning null or 0 just sounds incorrect if your code has pretty good abstraction. I just wanted to know if I could actually implement this in code, or if I'd have to just leave it to theory.

There's a good difference between programming-point-of-view exception and analyst-point-of-view exception.

Note: I've given a really simple and silly example, this is not quite my case.
Note 2: I know returning null would be the ordinary thing, but I'm required to have properly abstracted and OO code, and, personally, I see no harm in this.

Answer

Asaph picture Asaph · Jan 25, 2010

Throwable also creates a stacktrace when it's created. From the java docs for Throwable:

throwable contains a snapshot of the execution stack of its thread at the time it was created.

So in terms of overhead with regards to creating a stacktrace, there should be no difference between Exception and Throwable.

If you are using exceptions for "exceptional events" (as you should be), then you shouldn't be too concerned with the overhead of a stacktrace. An exceptional event occurs rarely in running code. So Exceptions shouldn't impact the performance of normal code in any significant way.