exceptions in static initializers



Ever so often I find side remarks in
postings that exceptions in static
initializers are a pain/bad/hard to
track/etc. I wonder why this seems
to be so common?

Let me elaborate: There are two
completely different cases of
exceptions:

a) The exception is triggered by a
bug, i.e. the situation is completely
under the control of the programmer and
he messed it up: The line

"bla".matches("(");

will result in a PatternSyntaxException
and the programmer should have known better.

b) The exception is a true exception, i.e.
the programmer has no chance at all to
prevent it to happen:

"bla".matches(getRegexpFromUser())

I would most probably not write a static
initializer where (b) might happen, but
case (a) exceptions are quite common.

I simply write then

static {
try {
// do stuff which should not
// throw except for a bug
} catch( SomeException e ) {
throw new Error("bug", e);
}
}

Now if I screwed up, I get the "bug"
exception with a nice stack trace.
What is wrong about it?

The only thing I could think of is
that unit testing is a bit strange
for those initializers.

Harald.

.



Relevant Pages

  • Re: [PHP] E_RECOVERABLE_ERROR - 5.1.6 to 5.2.0
    ... although the program contains a bug it hasn't crashed, ... If fopendidn't throw and the programmer didn't check the return ... (catch the exception in your version), ... over returning error codes and not DOING anything with them? ...
    (php.general)
  • Re: Where should I use assert(<pointer>!=NULL)?
    ... If using automated testing tools the use of 'assert' might very well be ... This first case assumes that a NULL-valued 'ptr' is an exceptional ... me that while a runtime check / exception throw will ensure handling of this ... precisely because the programmer knows the possibility will be handled. ...
    (alt.comp.lang.learn.c-cpp)
  • Exceptions and Error Handling
    ... I've been coding Java for a while but I'm trying to improve my coding so I'd ... fail on an IOException, ... I was the programmer, it would probably save me time if I knew that the file ... Given an exception occuring in a ...
    (comp.lang.java.help)
  • Re: Choosing not to throw exceptions like IllegalArguementException
    ... preventing debug from happening at all. ... like a recipe for converting easily debugged problems into subtle wrong ... Imagine the TreeCellRenderer wich throw an exception, and prevent the JTree from any repaint success, only because some bug happened before, which broke a specific assumption, and now there is the "impossible case" happening. ...
    (comp.lang.java.programmer)
  • Re: Find rare bugs - SEH and c++ exception handling
    ... Unfortunately the bug occurs only "on the read" it's not that easy (or ... I can't introduce MessageBoxes because they ... It really seems that I neet a lot of patience. ... When the kernel detects an application exception, ...
    (microsoft.public.pocketpc.developer)