2014-10-17 100 views
3

林有點不確定這是否:多個語句在try/catch塊 - Java的

try{ 
     worldHeight = Integer.parseInt(JOptionPane.showInputDialog("How many cells high will the world be?: ")); 
     } 
     catch (NumberFormatException e){ 
      JOptionPane.showMessageDialog(null, "You have not entered a valid number"); 
     } 

    try{ 
     worldWidth = Integer.parseInt(JOptionPane.showInputDialog("How many cells wide will the world be?: ")); 
     } 
     catch (NumberFormatException e){ 
      JOptionPane.showMessageDialog(null, "You have not entered a valid number"); 
     } 

會做同樣的事情:

try{ 
     worldHeight = Integer.parseInt(JOptionPane.showInputDialog("How many cells high will the world be?: ")); 
     worldWidth = Integer.parseInt(JOptionPane.showInputDialog("How many cells wide will the world be?: ")); 
     } 
     catch (NumberFormatException e){ 
      JOptionPane.showMessageDialog(null, "You have not entered a valid number"); 
     } 

基本上要用戶輸入一個數字,如果它不是一個數字異常被拋出並且用戶被重新請求一個數字?

謝謝

回答

3

在第一個示例中,使用兩個單獨的try...catch塊,似乎在引發異常時,您只是顯示一個對話框,而不是停止控制流。

因此,如果在第一個try...catch中出現異常,控制將繼續到第二個try...catch,並且將要求用戶輸入第二個號碼,而不管她沒有正確輸入第一個號碼。

在第二示例中,如果在所述第一try...catch一個異常,則用戶將不與第二個問題提出,因爲控制不會在try塊內繼續,而是catch塊的結束之後。

0

是的,這將工作(幾乎)相同。在try catch塊中,它只會在發生錯誤的地方停止執行。如果它在第一行發生錯誤,第二行將永遠不會在第二個選項中執行。這是唯一的區別,在第一個選項中,無論第一行(輸入)是否引發錯誤,都會執行第二行(輸入)。