JAVA:尝试捕获异常

时间:2015-03-23 22:00:44

标签: java try-catch

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

  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中,并立即抛出所有异常。这似乎是一种很好的方式,但我不确定它是否是一种好的做法

3 个答案:

答案 0 :(得分:0)

您还可以执行以下操作:

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

答案 1 :(得分:0)

我希望这可以解释何时应该捕获异常: 当我知道如何处理异常时:

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

如果我不知道如何处理异常:

    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 >_<
      }
    }

就像你看到的那样,何时或如何捕获异常&#34;应该&#34;取决于你如何处理&#34;那个例外。 希望能帮助到你。

答案 2 :(得分:-1)

您可以立即执行catch (Exception e){}来捕获所有这些内容。

然而,大多数情况下,实际上在发生事件时发生异常事件更有用,而不是仅仅在结束时捕获它们。