Is it possible to create a class which throws an Exception in the constructor. Yes.
The following shows one example.
public class Foo {
public Foo() {
throw new RuntimeException();
}
public void calculate() {
System.out.println("I am now calculating");
}
}
The class above will always throw a run time exception whenever someone tries to instantiate it. Is there a way round it and call the calculate method? Yes there is. The class below actually succeeds. The solution is that Foo is not a final class. I will sub-class it and operate on that instance.
public class Bar extends Foo {
public static Foo foo;
@Override
protected void finalize() throws Throwable {
foo = this;
}
}
Create a runner which will do the job.
public class Runner {
public static void main(String...args) {
try {
Foo foo = new Bar();
} catch (Exception e) {
System.out.println("Just to show exception caught " + e.getMessage());
}
System.gc();
System.runFinalization();
System.out.println("My instance " + Bar.foo);
Bar.foo.caluclate());
}
}
This example shows that you should always use the final word when you do not want people to be able to create incomplete instances.
0 comments:
Post a Comment