When to create exception objects

I got this question today, thought I'd share my answer here:

Q:

People are creating and throwing an exception at the same place, usually when a problem occurred.

Does it hurt if someone creates an exception in a static construction, then throw it later?

A:

We do this in the runtime for out of memory exceptions and some other cases. 
 
Generally speaking we think it is good practice to have a helper method that creates the exception to facilitate sharing of the code if nothing else.
 
Creating exceptions in advance is often problematic because they have instance data which may not be applicable to describe the specific problem.  I would say that if you have any exceptions for which the allocation of the exception is something you're concerned about you have made a giant mistake in the first place and no amount of precreation will rescue you.
 
So, general advice:

  • don't throw expensive exceptions in any scenario which you expect to have decent perf
  • use a helper method to create and throw the exception (by ID for instance)
  • don't have a lot of statically created exceptions because instance data makes them less sharable than first appears

But whatever you do, don't make a decision based on (just) anecdotal wisdom like this:  rather use these ideas to suggest experiments that you should conduct and measure to get the right answer.

More advice on throwing exceptions can be found here.