【发布时间】:2016-04-04 04:55:05
【问题描述】:
我有一个程序,它声明了一组 Apartment 对象。每个公寓都有地址、编号、卧室数量和租金。初始化数组时,每个公寓都被赋予一个字符串,Apartment 类的构造函数将该字符串转换为值。该程序是一个使用多个类的异常抛出和捕获的测试研究。
目前一切正常,Apartments 被创建,字符串被正确地转换为对象参数,异常被正确地抛出和捕获,然而,目前,当异常被捕获时,程序结束。我不确定如何处理这个问题。我相信我可以重组程序,以便在 Apartment 构造函数本身中捕获异常,但如果这不起作用,那将是浪费时间,所以我决定在这里搜索,然后询问首先。
这是程序中“main”类的代码,下面是当前的输出:
public class ThrowApartmentException
{
public static void main(String[] args)
{
// this program uses three classes, the ThrowApartmentException class is the "main" class, it's what you run to use the program. The Apartment class is used to create
// apartment objects, and it converts apartment Strings into values, checks those values for validity, and throws an exception if those values are wrong. This exception
// is an ApartmentException, which is the third class. It takes the apartment string as an argument and simply prints a message stating that the apartment failed to be
// instantiated.
// this class creates an array of 6 apartment objects, with both valid and invalid values, and an appropriate message is displayed when one is instantiated successfully
// and one is not.
Apartment[] apartments = new Apartment[6];
// apartment string parameter is formatted "address, number, rooms, rent".
try {
apartments[0] = new Apartment("123 Fake Street, 456, 3, 1500"); // valid.
apartments[1] = new Apartment("21 Blizzard Avenue, 333, 2, 2600"); // invalid rent.
apartments[2] = new Apartment("6 Brr Street, 23, 1, 1000"); // invalid number.
apartments[3] = new Apartment("25 Boat Lane, 324, 5, 1200"); // invalid rooms.
apartments[4] = new Apartment("47 Kenneth Street, 550, 1, 1000"); // valid.
apartments[5] = new Apartment("36 Sanders Drive, 230, 1, 1300"); // valid.
}
catch(ApartmentException mistake) {
}
}
}
-----------------------------------------
Output:
Apartment 123 Fake Street, 456, 3, 1500 was successfully initialised.
Apartment 21 Blizzard Avenue, 333, 2, 2600 failed to be instantiated, one or more of the values was outside of valid range.
我认为可以解决问题的当前选项是:
1:将每个对象实例化放在它自己的 try/catch 块中。
2:重构程序,以便在 Apartment 构造函数中执行 try/catch 块。
3:如果了解某种允许像这样的唯一对象实例化的循环格式化方法,我可能会使用字符串数组,但这似乎是一个非常尴尬的管道胶带解决方案,而不是实际的解决方案。
【问题讨论】:
-
1 和 2 都应该工作。我认为 2 更好,因为它更健壮,而你 Don't Repeat Yourself。但是,这实际上并不是一个问题,所以我将投票结束(这将使您有机会将其编辑为适当的问题)