[英]JAVA:Try catch Exceptions
我不确定在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中,并立即抛出所有异常。 这似乎是一种很好的整洁方法,但是我不确定这是否是一种好习惯
您还可以执行以下操作:
public static void main(String[] args) {
try {
...
} catch(IllegalCustomerIDException e) {
...
} catch(IllegalProductCodeException e) {
...
} catch(IncorrectPurchaseOrderException e) {
...
} catch(CustomerNotFoundException e) {
...
} catch(IOException e) {
...
}
}
我希望这能解释您何时应该捕获异常:当我知道如何处理异常时:
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 >_<
}
}
如您所见,何时或如何捕获异常“应该”取决于您如何“处理”该异常。 希望能帮助到你。
您可以执行catch (Exception e){}
来一次捕获所有这些。
但是,在大多数情况下,在发生事件的时间/地点进行一些实际的异常操作比在最后捕获所有异常要有用得多。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.