2013-05-01 42 views
0

嘿,大家我有一個關於異常try-catch語句的問題。在練習題中,用戶輸入一定長度的字符串。如果用戶輸入的字符串長度大於20,則會引發異常。現在我似乎已經按順序設置了所有東西,但是真正讓我困惑的是將什麼放在try塊中。任何人都可以用僞代碼解釋,或者通過解釋我需要輸入什麼來運行它?異常處理try-catch語句字符串長度

此外,我有一個問題關於與我的catch(StringTooLongException e) catch語句。我已經創建了另外兩個程序來處理一個繼承的類和一個使用我創建的名稱來解決同樣的問題的類,並且使用了try-catch語句。這就是StringTooLongException的來源。我的問題是,你怎麼知道使用什麼異常名稱?我知道有一些內置於java的一般異常,但我只是有點困惑。

感謝

這裏是我的代碼:

import java.util.Scanner; 

public class StringTooLongExceptionModified{ 

    public static void main(String[] args){ 
     String input; 


     Scanner myScan = new Scanner(System.in); 
     System.out.println("Enter a string(DONE to quit): "); 
     input = myScan.nextLine(); 

     while(!input.equals("DONE")){ 

      try{ 




      } 
      catch(StringTooLongException e){ 
       System.out.println ("Exceeds string length: " + input); 
      } 

      System.out.println("Enter a string(DONE to quit): "); 
      input = myScan.nextLine(); 


     } 
    } 
} 

回答

1

好像你正在尋找:

try{ 
    if (input.length() <= 20) { 
     // do stuff with your input 
    } else { 
     throw new StringTooLongException("'" + input + "' is longer than 20"); 
    } 
} catch(StringTooLongException e){ 
    System.out.println ("Exceeds string length: " + input); 
} 
+0

與問候「你怎麼知道該怎麼使用異常的名字嗎?」 如果您的'StringTooLongException'類的子類爲'Exception',那麼您可以使用'catch(StringTooLongException e){...}' 其他預定義的異常可以通過[this]找到(http://docs.oracle.com /javase/6/docs/api/java/lang/Exception.html) – Adeeb 2013-05-01 01:13:49

+0

感謝您輸入jlordo,但現在每次運行它時,都不會拋出異常。如果我輸入更多長度超過20的字符串,它會繼續運行。任何想法可能是錯誤的? – user2045470 2013-05-01 01:35:50

+0

另外,謝謝Adeeb。這清除了我有關使用哪個異常名稱的問題。 – user2045470 2013-05-01 01:36:55