【问题标题】:How to create a for statement to handle my Exception如何创建一个 for 语句来处理我的异常
【发布时间】:2015-02-28 23:28:39
【问题描述】:

我之前创建了一个包含 customerList 的程序,该程序通过他们的 courseList 向每个客户添加课程。现在我必须修改程序(有一个新的客户列表)以抛出一个名为 CustomerNotEnrolledException 的异常,如果一个客户没有注册任何课程。

我从Customer 类中的createInvoice 方法抛出异常,并在测试类中处理它。我的问题是:

我将如何编写for 循环来检查每个客户中的这些课程。

我之前声明的两个数组是:

ArrayList<Course> courseList = new ArrayList<Course>();
ArrayList<Customer> customerList = new ArrayList<Customer>();

【问题讨论】:

  • 完全不清楚。异常由 try catch 而非 for 语句处理。客户如何拥有他们未注册的课程,如果它在他们的课程列表中。大概还有其他已注册客户的课程列表?
  • 取自How to ask“现在你已经准备好提出你的问题,深呼吸,从头到尾通读一遍。假装你正在看它第一次:这有意义吗?”你必须以别人可以帮助你的方式来写你的问题。就目前而言,您的问题没有提供有关该问题的足够信息:CourseCustomer 有什么关系? Customer 是否有Courses 的列表,或者Course 是否包含Customers 的列表?必须有一种方法可以检查对象的相关性
  • 是的,我有一个新的客户和课程列表。每个客户都有一个他们注册的课程列表。如果客户没有参加任何课程,我想在测试课中抛出异常并处理它。你能帮帮我吗?

标签: java for-loop arraylist exception-handling throws


【解决方案1】:

根据您的构思方式,它可能非常简单 您可以在构造时检查调用代码是否提供了非空的课程列表,或者您可以有一个检查它的方法。如果课程列表为空或为空,则抛出异常

示例: 在您的createInvoice 方法中,您可以在进一步处理之前调用checkCourseEnrollment()

 public class Customer {
    private List<Course> courses;

    public Customer() {}
    public Customer(List<Course> courses) throws CustomerNotEnrolledException {

        // Check here if the constructor receives any course list
        // If not trigger the exception 

        if (null == courses || courses.size() == 0) {
            throw new CustomerNotEnrolledException(/* potential parameters here */);
        }

        // continue constructor initialization process here
        this.courses = courses;
    }

    public void checkCourseEnrollment() throws CustomerNotEnrolledException {

        if (null == this.courses || this.courses.size() == 0) {
            throw new CustomerNotEnrolledException(/* potential parameters here */);
        }

    }

}

【讨论】:

    猜你喜欢
    • 2012-03-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-10-24
    • 2014-02-15
    • 2012-04-15
    相关资源
    最近更新 更多