gpt4 book ai didi

JAVA: try catch 异常

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

我不确定在主方法中抛出多个异常的最佳方法。这是我采取的方法,我想知道这种方法是否正确

  public static void main(String[] args)  {

File nFile = new File("ProductData.txt");
File file = new File("CustomerData.txt");
File pFile = new File("PurchaseOrderDataFile.txt");
try {
Scanner pScan = new Scanner(pFile);
Scanner scan = new Scanner(file);
//Makes ElectronicsEquipmentSupplier object with the month and year product array
ElectronicsEquipmentSupplier ees = new ElectronicsEquipmentSupplier
(1, 12, InputFileData.readProductDataFile(nFile));
//Adds successive customer records to suppliers customer list
for (int i = 0; i < 28; i++) {
ees.addNewCustomer(InputFileData.readCustomerData(scan));
}
for (int i = 0; i <= 24; i++) {
String poByMonth = InputFileData.readPurchaseOrderDataFile(pScan); //Brings list in by months
String[] purchaseOrder = poByMonth.split("\\s+");
ees.startNewMonth(); //When the months are split by the @ it adds a new month
for (int j = 0; j <= purchaseOrder.length - 1; j++) {
String[] result = purchaseOrder[j].split("#");
int qty = Integer.parseInt(result[3]);
ees.addNewPurchaseOrder(result[0], result[1], result[2], qty);
double orderTotal = 0;
for (Product p : ees.getRangeOfProducts()) {
if (p.getProductCode().equals(result[2])) {
orderTotal = p.getPricePerUnit() * qty;
}
}
CustomerDetails customer = ees.getDetails().findCustomer(result[1]);
customer.setTotalPrice(orderTotal + customer.getTotalPrice());
if (result[1].substring(0, 1).equals("P")) {
System.out.println("Customer ID: " + (result[1]));
System.out.println("Discount: " + customer.getDiscountRate());
}
}
}
} //Catches exceptions
catch(IllegalCustomerIDException| IllegalProductCodeException |
IncorrectPurchaseOrderException | CustomerNotFoundException | IOException ex){
//Outputs exceptions if they are caught
System.out.println(ex);
}
}

如您所见,我已将所有内容放入一个大型 try catch 中,并立即抛出所有异常。这似乎是一个很好的简洁方法,但我不确定这是否是一个好的做法

最佳答案

您还可以执行以下操作:

public static void main(String[] args)  {
try {
...
} catch(IllegalCustomerIDException e) {
...
} catch(IllegalProductCodeException e) {
...
} catch(IncorrectPurchaseOrderException e) {
...
} catch(CustomerNotFoundException e) {
...
} catch(IOException e) {
...
}
}

关于JAVA: try catch 异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29221280/

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