简体   繁体   English

JAVA:尝试捕获异常

[英]JAVA:Try catch Exceptions

I am unsure as to the best way to throw multiple exceptions in the main method. 我不确定在main方法中引发多个异常的最佳方法。 This is the approach I have taken, I was wondering if this way is correct 这是我采取的方法,我想知道这种方法是否正确

  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);
        }
    }

As you can see I have put it all in one large try catch and thrown all the exceptions at once. 如您所见,我将所有内容放入一个大的try catch中,并立即抛出所有异常。 It seemed a nice neat way of doing it but I'm unsure as to whether or not it is good practice 这似乎是一种很好的整洁方法,但是我不确定这是否是一种好习惯

You could also do something like: 您还可以执行以下操作:

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

I hope this explains when you should catch exceptions: When i know how to handle the exceptions: 我希望这能解释您何时应该捕获异常:当我知道如何处理异常时:

class SomeWeirdName{
  void someMethod(){
    try{
      // your logic here >_<
    }
    catch(ExceptionTypeA A){
      doSomething1();
    }
    catch(ExceptionTypeB B){
      doSomething2();
    }finally{
      somethingElse();
    }
  }
}

If I don not know how to handle the exception: 如果我不知道如何处理该异常:

    class SomeWeirdName{
      // i don't know how to handle the exception, so no need to catch them
      // maybe someone else is gonna catch the exception later in some 
      // other class
      void someMethod() throws ExceptionTypeA, ExceptionTypeB{        
          // your logic here >_<
      }
    }

Like you see, when or how you catch the exception "should" depend on how you "handle" that exception. 如您所见,何时或如何捕获异常“应该”取决于您如何“处理”该异常。 Hope it helps. 希望能帮助到你。

You could just do a catch (Exception e){} to catch all of them at once. 您可以执行catch (Exception e){}来一次捕获所有这些。

However, most of the time it's more useful to actually do something with a exception when/where it happens, instead of just catching them all at the end. 但是,在大多数情况下,在发生事件的时间/地点进行一些实际的异常操作比在最后捕获所有异常要有用得多。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM