Re: catching exceptions in subclass' constructor?
On Mon, 1 Sep 2008, bugbear wrote:
So I tried:
public B() {
try {
this(10);
} catch(NoSuchFieldException e) {
throw new IllegalStateException(e);
}
}
but the compiler says:
" call to this must be first statement in constructor"
I would welcome advice on how to achieve my goal (a parameterless
constructor for B that does not throw an exception).
Okay, the first point is that what you're trying to do is a Bad Idea.
Checked exceptions are there for a reason - they're failure modes which
have to be handled. If you convert to a RuntimeException, you make it very
easy for clients of your subclasses not to do error handling properly.
That's not good.
Which leads me to the second point. Good news: it's impossible to do what
you want in java. As the compiler said - the super/this call has to be the
first thing in the constructor.
However, there is a possible way out. The thing is, although you can't do
this in java, you *can* do it in bytecode. It's entirely possible to have
a super/this call with an exception handler covering it. There's just no
way to express it in java. If you're prepared to do some bytecode hacking
- perhaps using an ant task to integrate it into your build process - you
can do it. If you want proper java, i can't think of a solution.
Honestly, though, i'd just declare the constructors with throws clauses in
your subclasses. It's two lines of boilerplate code and some braces in
each one, hardly worth getting excited about.
If you want to create instances without having to deal with checked
exceptions, consider a helper method:
static B create(Class<? extends B> cl) {
try {
return cl.newInstance() ;
}
// your exception:
catch (NoSuchFieldException e) {
throw new IllegalStateException(e);
}
// nonspecific exceptions:
catch (IllegalAccessException e) {
throw new RuntimeException(e) ;
}
catch (InstantiationException e) {
throw new RuntimeException(e) ;
}
}
tom
--
Our only chance for survival is better engineering. -- James Dyson