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

时间:2016-04-04 04:55:06

标签: java class exception

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

所有内容当前正在工作,公寓已创建,字符串已正确转换为对象参数,并且异常被正确抛出并捕获,但是,当前捕获异常时,程序结束。我不确定该怎么办这个问题。我相信我可以重新构建程序,以便在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 个答案:

答案 0 :(得分:1)

这就是我要做的事情:

1-如果向print()传递了无效的输入,那么Apartment Class会抛出异常(在您的情况下为ApartmentException

2-使用List代替以下数组:

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