Re: Clean up after exception thrown in constructor
On Tue, 15 Apr 2008 15:38:38 +0200 Philipp wrote:
What would be a better approach to this problem, so that if construction
fails for whatever reason, the system is left in a pristine state?
public class Car {
private static List<String> nameList = new ArrayList<String>();
Prolly not a good idea, as it is not threadsafe.
private String name;
public Car(String name){
this.name = name;
}
Create an initialize-method where you add the name to the list (register).
public void register() {
nameList.add( name );
}
public static class Ford extends Car{
public Ford(String name, int wheels){
super(name);
if(wheels > 4){
throw new IllegalArgumentException("Too many wheels");
}
else {
register();
}
}
}
Then you can first check the arguments and postpone the initialization
until you are pretty sure about that the arguments are correct. But of
course you can then forget to call register..
Otherwise you can call remove in the if-part
if(wheels > 4){
remove();
throw new IllegalArgumentException("Too many wheels");
}
Neither way is very elegant. A better way would be a car factory which does
the registration and also is thread safe:
class CarFactory {
private List<String> carNames;
public <T extends Car> create( Class<T> clazz ) {
T result = ... use reflection to create an instance...
register( result );
}
private synchronized void register(Car c) {
carNames.add(c.getName());
}
}
Jan