2016-05-17 43 views
-1

嘿所以在我的班級我這樣寫:的try/catch不顯示的異常錯誤消息

public void setId(String id) { ... 
    if (id.matches("[a-zA-Z]{3}-\\d{4}")) { 
     this.id = id; 
    } else { // id is invalid: exception occurs 
     throw new IllegalArgumentException("Inventory ID must be in the " 
      + "form of ABC-1234"); 
    } 

} 

然後在我的主要節目,我這樣做:

while (idLoopTrigger == true) { 
     try { 

      System.out.println("Please enter id: "); 
      id = in.nextLine(); 

      if (id.matches("[a-zA-Z]{3}-\\d{4}")) { 
       idLoopTrigger = false; 
      } 

     } catch (Exception ex) { 

      //print this error message out 
      System.out.println(ex.getMessage()); 

     } 

    } 

所以它會循環,直到用戶輸入正確的信息,但不會顯示我的課程中的異常信息。思考?

+1

你不要在循環中的任何地方調用'setId()'。沒有例外被拋出。 –

+0

您的代碼在try塊中是否會引發異常。除非它拋出它不會執行catch塊 –

+0

你不是在任何地方調用'setId()',但是你實際上正在測試'nextLine'中的每個'id',所以你永遠不會檢測到任何會拋出異常的無效id。 – 2016-05-17 23:19:35

回答

1

它看起來像是在main()中近似setId()方法的內容而不是調用它。

我不知道哪裏該setId()方法應該是爲了活着,但假設它是在同一個類定義爲您的main()

while (idLoopTrigger == true) { 

    try { 
     System.out.println("Please enter id: "); 
     id = in.nextLine(); 
     setId(id); 
     idLoopTrigger = false; 

    } catch (Exception ex) { 

     //print this error message out 
     System.out.println(ex.getMessage()); 
    } 

} 

這似乎是你要找的內容應至少接近對於。

+0

像一個魅力工作 - 謝謝澄清! –