需要帮助捕获 For Each 循环上的 ArrayIndexOutOfBoundsException (Java) [duplicate]

Need Help Catching An ArrayIndexOutOfBoundsException On A For Each Loop (Java) [duplicate]

提问人:Erik Sulin 提问时间:11/7/2023 更新时间:11/7/2023 访问量:61

问:

HW3.java

导入 java.util.Scanner;

公共类 HW3 {

//Method Establishes Scanner For Inputing Hour
public static int Scanner() {
    Scanner x = new Scanner(System.in);
    int pay = x.nextInt();
    return pay;
}
        
public static void main(String args[]) {
    //Asks For Hour Input, Input Hours Into Variable
    System.out.println("Input Hours");
    int hour = Scanner();

    //Establish Array Of Employees With Name And Wage Categories
    Employee [] employee = new Employee[4];
    employee [0] = new Employee("Shinji Ikari", 15.50);     
    employee [1] = new Employee("Rei Ayanami", 21.35);  
    employee [2] = new Employee("Asuka Langley Soryu", 2.12);
    employee [3] = new Employee("Kaworu Nagisa", 20.01);
    
    //For Loop Running The showText Method From Employee.java For Each Employee In Array 
    try {
        for (Employee e : employee)     
            e.showText(hour);       
    } catch(ArrayIndexOutOfBoundsException oob) {
        System.out.println("NO");
    }   
}   

}

员工.java

公共类 Employee {

//Sets Private Variables That Defines "Employee"
private String name;
private double wage;
private double totalpay;

    //Employee Constructors For Name And Wage
    public Employee(String employeename, double hourlypay) {
        name = employeename;
        wage = hourlypay;
    }   
    
    //Returns The Name Value        
    public String getName() {           
        return name;        
    }
    
    //Sets ASnd Updates Name
    public void setName(String ename) {         
        name = ename;   
    }       
    
    //Returns The Wage Value
    public double getWage() {
        return wage;
    }
    
    //Sets And Updates Wage
    public void setWage(double hourlypay) {
        wage = hourlypay;
    }
    
    //Method That Subtracts A 30% Tax From Base Hourly Pay  
    public double getTotalPay() {       
        totalpay = wage - (wage*0.3);
        return totalpay;
            }

    //Method Takes Name, Wage, and Totalpay From Employee.java Alongside Hour From HW3.java To Place Them In The Printed Statement
    public void showText(int hoursworked) {
        try {System.out.printf("The employee " +name+ ", who earns $%.2f per hour, worked for " +hoursworked+ " hours last week and took home $%.2f after taxes.\n", wage, getTotalPay()*hoursworked);
        } catch(ArrayIndexOutOfBoundsException oob) {
            System.out.println("Error");
        }
    }

}

在这个每周薪水估算器程序中,当从我的员工数组中提取员工时,我需要捕获可能的 ArrayIndexOutOfBoundsException。我不知道如何测试我当前放置的异常程序是否正确,因为我不知道如何格式化每个循环以尝试循环超出我当前在主方法中的四个员工。我当前的异常程序是否正确放置在循环中,还是需要将其放置在其他位置?

java 数组 foreach catch-exception

评论

7赞 Robby Cornelissen 11/7/2023
永远没有理由抓住.您可以事先测试数组索引,增强的 for 循环永远不会越界。不要使用异常来控制程序的流程。ArrayIndexOutOfBoundsException
0赞 Roland J. 11/7/2023
另一个问题:为什么要在 showText 方法中捕获 ArrayIndexOutOfBoundsException?此方法不执行任何数组操作。

答:

0赞 Stephen C 11/7/2023 #1

如果未引发异常,则无法捕获异常。如果抛出 try / catch 语句它将捕获......但它没有被扔掉。ArrayIndexOutOfBoundsException

try {
    System.out.printf("The employee " + name + 
         ", who earns $%.2f per hour, worked for " +
         hoursworked + 
         " hours last week and took home $%.2f after taxes.\n", 
         wage, getTotalPay() * hoursworked);
} catch (ArrayIndexOutOfBoundsException oob) {
    System.out.println("Error");
}

代码块中的代码根本不在数组上运行,因此无法引发异常。

(顺便说一句:printf 也被误导了。您同时使用字符串连接格式设置。您只需格式化即可完成所有操作,并且代码将更具可读性。

try {
    for (Employee e : employee)     
        e.showText(hour);       
} catch (ArrayIndexOutOfBoundsException oob) {
    System.out.println("NO");
}

这是在数组上操作的,但它以一种保证不会超出数组边界的方式进行操作。

如果你想要上述原因导致该异常(以便你可以捕获它),你可以像这样重写循环:

try {
    for (int i = 0; i < 9999; i++) // this loop is deliberately wrong    
        employee[i].showText(hour);       
} catch (ArrayIndexOutOfBoundsException oob) {
    System.out.println("NO");
}

现在,当 is 时,您将收到一个异常。但是你不会/不应该在真正的程序中这样做。应避免使用异常处理来实现“正常”控制流。(尽管“正常”控制流的含义还有待解释!i4


代码是否正确?

是和否;见上文。

  • 是的,因为如果抛出异常,您会捕获异常。这段代码确实可以编译。
  • 否,因为不会引发异常。保证。试图捕获无法抛出的(未经检查的)异常的代码是多余的和误导性的......因此是错误的。