2012-03-22 74 views
17

我試圖拋出一個異常(不使用try catch塊),並且我的程序在異常拋出後立即完成。有沒有辦法在拋出異常之後繼續執行我的程序?我拋出了我在另一個類中定義的InvalidEmployeeTypeException,但是我希望程序在拋出後繼續執行。在java拋出異常後繼續執行

private void getData() throws InvalidEmployeeTypeException{ 

    System.out.println("Enter filename: "); 
    Scanner prompt = new Scanner(System.in); 

    inp = prompt.nextLine(); 

    File inFile = new File(inp); 
    try { 
     input = new Scanner(inFile); 
    } catch (FileNotFoundException ex) { 
     ex.printStackTrace(); 
     System.exit(1); 
    } 

    String type, name; 
    int year, salary, hours; 
    double wage; 
    Employee e = null; 


    while(input.hasNext()) { 
     try{ 
     type = input.next(); 
     name = input.next(); 
     year = input.nextInt(); 

     if (type.equalsIgnoreCase("manager") || type.equalsIgnoreCase("staff")) { 
      salary = input.nextInt(); 
      if (type.equalsIgnoreCase("manager")) { 
       e = new Manager(name, year, salary); 
      } 
      else { 
       e = new Staff(name, year, salary); 
      } 
     } 
     else if (type.equalsIgnoreCase("fulltime") || type.equalsIgnoreCase("parttime")) { 
      hours = input.nextInt(); 
      wage = input.nextDouble(); 
      if (type.equalsIgnoreCase("fulltime")) { 
       e = new FullTime(name, year, hours, wage); 
      } 
      else { 
       e = new PartTime(name, year, hours, wage); 
      } 
     } 
     else { 


      throw new InvalidEmployeeTypeException(); 
      input.nextLine(); 

      continue; 

     } 
     } catch(InputMismatchException ex) 
      { 
      System.out.println("** Error: Invalid input **"); 

      input.nextLine(); 

      continue; 

      } 
      //catch(InvalidEmployeeTypeException ex) 
      //{ 

      //} 
     employees.add(e); 
    } 


} 

回答

4

試試這個:

try 
{ 
    throw new InvalidEmployeeTypeException(); 
    input.nextLine(); 
} 
catch(InvalidEmployeeTypeException ex) 
{ 
     //do error handling 
} 

continue; 
+25

你不覺得這不是一個如何使用異常的好例子嗎? – manub 2012-03-22 17:17:42

+1

這工作完美。我能夠處理錯誤處理並繼續執行 – 2012-03-22 17:37:31

+0

我花了一段時間才明白,爲什麼這段代碼在有禮貌地開頭的評論中「不是一個好例子」。 'input.nextLine();'從不執行。 – Reg 2017-12-08 13:05:18

30

如果拋出異常,則方法執行將停止,異常將引發到調用方法。 throw總是中斷當前方法的執行流程。一個try/catch塊是您在調用可能拋出異常的方法時可以編寫的內容,但拋出異常僅表示由於異常情況而終止了方法執行,並且異常通知調用方方法。

查找本教程的異常以及它們如何工作 - http://docs.oracle.com/javase/tutorial/essential/exceptions/

4

如果你有,你想拋出一個錯誤的方法,但你想要做一些清理工作在你的方法,你可以把代碼放在try塊中,然後把清理放到catch塊中,然後拋出錯誤。

try { 

    //Dangerous code: could throw an error 

} catch (Exception e) { 

    //Cleanup: make sure that this methods variables and such are in the desired state 

    throw e; 
} 

這樣的try/catch塊是不實際處理錯誤,但它讓你有時間做的東西的方法終止,仍然保證了誤差上給調用者才能通過。

這樣做的一個例子是如果變量在方法中發生變化,那麼該變量就是錯誤的原因。可能需要恢復變量。