我不确定在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中,并一次性抛出所有的异常。这似乎是一种很好的干净利落的方式,但我不确定这是否是一种好的做法
发布于 2015-03-24 06:06:31
你也可以这样做:
public static void main(String[] args) {
try {
...
} catch(IllegalCustomerIDException e) {
...
} catch(IllegalProductCodeException e) {
...
} catch(IncorrectPurchaseOrderException e) {
...
} catch(CustomerNotFoundException e) {
...
} catch(IOException e) {
...
}
}发布于 2015-03-24 06:37:08
我希望这能解释什么时候你应该捕捉异常:当我知道如何处理异常时:
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 >_<
}
}正如您所看到的,何时或如何捕获异常“应该”取决于您如何“处理”该异常。希望能有所帮助。
发布于 2015-03-24 06:03:11
你可以只做一次catch (Exception e){}来一次捕获所有的它们。
然而,大多数时候,在发生异常的时候实际做一些事情会更有用,而不仅仅是在结束时捕获所有的异常。
https://stackoverflow.com/questions/29221280
复制相似问题