嗨,大家好,我的程序並沒有真正捕獲任何錯誤,即當我輸入一個字母而不是有效數字時,它確實發現錯誤,但它不返回菜單,它只顯示語句。當我在switch語句之外使用一個數字,即5時,它只是循環回菜單而不顯示錯誤。我的代碼如下:如何使異常處理中的程序捕獲錯誤 - Java
public void runMenu() {
Scanner Option = new Scanner (System.in);
int x = 1;
int Choice = 0;
do{
try{
System.out.println("Choose Option");
System.out.println("");
System.out.println("1: Create Account");
System.out.println("2: Check Account");
System.out.println("3: Take Action");
System.out.println("4: Exit");
System.out.println("Please choose");
Choice= Option.nextInt();
switch (Choice) //used switch statement instead of If else because more effective
{
case 1:
CreateAccount();
break; //breaks iteration
case 2:
selectAccount();
break;
case 3:
Menu();
int choice = UserInput();
performAction(choice);
break;
case 4:
System.out.println("Thanks for using the application");
System.exit(0);
default:
throw new Exception();
// x=2; //if code doesn't run successfully then x !=2 leading to exception
}
}
爲什麼它應該返回菜單以防萬一拋出異常?你在catch塊中寫了一個'return'語句 – Rehman
John - 請注意,你最後編輯的問題已經使代碼不可編譯......並且一旦你修復了編譯錯誤,行爲將會不同。如果你想讓人們幫助你,不要做那種事。 –