gpt4 book ai didi

java - 捕获异常后继续程序,而不使用循环?

转载 作者:行者123 更新时间:2023-12-01 10:06:43 25 4
gpt4 key购买 nike

我有一个程序,它声明了一个 Apartment 对象数组。每间公寓都有地址、号码、卧室数量和租金价格。初始化数组时,每个公寓都会被赋予一个字符串,并且 Apartment 类的构造函数将该字符串转换为值。该程序是使用多个类进行异常抛出和捕获的测试研究。

目前一切都按预期工作,公寓已创建,字符串已正确转换为对象参数,并且正确抛出并捕获异常,但是,目前,当捕获异常时,程序结束。我不确定该怎么处理这个问题。我相信我可以重组程序,以便在 Apartment 构造函数本身内部捕获异常,但如果这不起作用,那就是浪费时间,所以我决定在这里搜索,然后询问首先。

以下是程序中“主”类的代码,其下方是当前输出:

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 block 中。

2:重构程序,使 try/catch block 在 Apartment 构造函数内执行。

3:了解格式化循环的某种方式,允许像这样的独特对象实例化,我可能可以使用字符串数组,但这似乎是一个非常尴尬的管道胶带解决方案,而不是实际的解决方案。

最佳答案

这就是我要做的:

1-如果向公寓类传递无效输入,则让其抛出异常(在您的情况下为ApartmentException)

2- 使用列表而不是数组,如下所示:

List<Apartment> myList = new ArrayList<Apartment>();

String[] desc = new String {"123 Fake Street, 456, 3, 1500", ... }

for(int i=0; i<desc.length; i++)
{
try
{
myList.add(new Apartment(desc[i]));
}
catch(ApartmentException mistake)
{
//do something
}
}

//at this point myList contains only valid listings

关于java - 捕获异常后继续程序,而不使用循环?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36394812/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com