H
HK
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.
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.