0
以下是從txt文件中讀取項目並確定事務是否已驗證的代碼。 我遇到了一個問題,當它引發異常格式的異常時,它跳出while循環,然後結束程序。我怎樣才能拋出異常,但之後繼續循環。我確實看過,有人表示每個手柄都有一個試塊,我只是想知道是否有更好的/更清潔的更有效的方法。在JAVA中停止while循環的異常
/*
* @Author: Louis Krueger
* @Desc: Homework assignment #2 exception handling
* @Version: 1.1
*/
package paymentApplication;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.InputMismatchException;
import java.util.Scanner;
public class MainHandle {
public static ArrayList<String> saPaymentList = new ArrayList<String>();
public static void main(String[] args) {
boolean bSkipTrans = false;
String sFileName = "";
String sPaymentInfo = "";
String[] saPaymentInfo = null;
Scanner keyBoard = new Scanner(System.in);
ArrayList<Payment> alPayments = new ArrayList<Payment>();
try{
System.out.println("Enter the file name to be read: ");
sFileName = keyBoard.nextLine();
Scanner inputStream = new Scanner(new FileInputStream("details.txt"));
System.out.println("Test1");
//loop to Create arraylist of PaymentInfo objects
while(inputStream.hasNextLine()) {
bSkipTrans = false;
Payment Payment = new Payment();
sPaymentInfo = inputStream.nextLine();
saPaymentInfo = sPaymentInfo.split(";");
if(saPaymentInfo.length == 1){
bSkipTrans = true;
throw new InvalidTransactionException();
}else{
if(saPaymentInfo.length > 1){
if (isInteger(saPaymentInfo[1]) == true){
Payment.setiTransValue(Integer.parseInt(saPaymentInfo[1]));
}else{
//throw exception
bSkipTrans = true;
throw new InvalidTransactionException("Error#1");
}
}
if(saPaymentInfo.length > 4){
Payment.setsCreditNumber(saPaymentInfo[4]);
}
if(saPaymentInfo.length > 3){
Payment.setsDate(saPaymentInfo[3]);
}
if(saPaymentInfo.length > 2){
Payment.setsName(saPaymentInfo[2]);
}
if(saPaymentInfo.length > 0){
if(saPaymentInfo[0] != "Cash"|saPaymentInfo[0] != "Credit"){
//throws exception
Payment.setsTransType(saPaymentInfo[0]);
}else{
bSkipTrans = true;
throw new InvalidTransactionException("Error#2");
}
}
}
if(bSkipTrans == true){
//throw exception
bSkipTrans = true;
throw new InvalidTransactionException("Empty line");
}else{
System.out.println(Payment.toString());
System.out.println("Payment Added");
System.out.println("-------------");
alPayments.add(Payment);
}
}
inputStream.close();
}catch(InputMismatchException e){
System.out.println("Error 1 has occured: " + e.getMessage());
}catch (FileNotFoundException e) {
e.printStackTrace();
} catch (InvalidTransactionException e) {
System.out.println("InvalidTransactionException thrown");
}finally{
System.out.println("Finally statement reached");
keyBoard.close();
System.exit(0);
}
}
public static boolean isInteger(String s) {
try {
Integer.parseInt(s);
} catch(NumberFormatException e) {
return false;
}
// only got here if we didn't return false
return true;
}
}
把while循環中嘗試使捕獲異常後循環仍在延續 – 2014-09-11 01:16:01
不能拋出異常*和*繼續,選擇一個或另一個。如果你想繼續,那麼只需記錄一個錯誤。 – 2014-09-11 01:16:13
異常意味着程序中出現問題,您必須處理它。如果沒關係,只要吃掉它並記錄下問題,否則你最好處理它,然後繼續或傳播給調用者。 – CharlesX 2014-09-11 01:22:08