我有这个代码应该为每个实例化抛出一个不同的异常。
Vehicle[] parkingLot = new Vehicle[5];
try
{
// NEGATIVE INPUT
parkingLot[0] = new Truck(1200.0, 2000, "Chevrolet", -8, new Person());
// NULL MANUFACTURER
parkingLot[1] = new Vehicle("", 8, new Person("John"));
// NULL OWNER NAME
parkingLot[2] = new Vehicle("Mitsubishi", 6, new Person(""));
// TOW CAPACITY OVER 1500
parkingLot[3] = new Truck(1700.0, 1000, "Nissan", 6, new Person("Joe"));
// LOAD CAPACITY OVER 8600
parkingLot[4] = new Truck(1200.0, 9000, "Nissan", 6, new Person("Frank"));
}
catch(Exception e)
{
System.out.println(e.getMessage());
}
由于我用来创建这些对象的值是硬编码的,所以我不能使用像
这样的循环parkingLot[index]
那么我应该如何设计我的代码,以便当一个实例化抛出异常时,仍然会尝试实例化其余的对象?
答案 0 :(得分:1)
我认为正确的解决方案是使用单独的try ... catch块但仅仅是为了挑战,这个(java 8)代码可以做你想要的:
Callable[] initializers = {
// NEGATIVE INPUT
() -> parkingLot[0] = new Truck(1200.0, 2000, "Chevrolet", -8, new Person()),
// NULL MANUFACTURER
() -> parkingLot[1] = new Vehicle("", 8, new Person("John")),
// NULL OWNER NAME
() -> parkingLot[2] = new Vehicle("Mitsubishi", 6, new Person("")),
// TOW CAPACITY OVER 1500
() -> parkingLot[3] = new Truck(1700.0, 1000, "Nissan", 6, new Person("Joe")),
// LOAD CAPACITY OVER 8600
() -> parkingLot[4] = new Truck(1200.0, 9000, "Nissan", 6, new Person("Frank"))
};
for (Callable i : initializers) {
try {
i.call();
} catch (Exception ex) {
System.out.println(e.getMessage());
}
}