2014-11-04 37 views
0

我有包括使用try/catch顯示了一些依賴於多個名字的,而基本分配錯誤輸入(使用數組)。如果輸入的數字太大,它可能仍會顯示名稱,但也必須給出出界限的錯誤。如果使用單詞或類似的東西,它需要給出格式錯誤。使用try/catch語句顯示,取決於輸入

到目前爲止,我的代碼工作得相當好,因爲它可以顯示出界失誤,但是當我輸入一個字,我沒有得到一個格式錯誤。

我也想知道是否將有可能引起(其中僅5接受的情況下),如果數量低於5到發生錯誤。

這裏是我的代碼:

class Program 
{ 
    static void Main(string[] args) 
    { 
     string[] names = new string[5] { "Merry", "John", "Tim", "Matt", "Jeff" }; 
      string read = Console.ReadLine(); 
      int appel; 

     try 
     { 
      int.TryParse(read, out appel); 
      for (int a = 0; a < appel; a++) 
      { 
       Console.WriteLine(names[a]); 
      } 


     } 



     catch(FormatException e) 
     { 
      Console.WriteLine("This is a format error: {0}", e.Message); 
     } 
     catch (OverflowException e) 
     { 
      Console.WriteLine("{0}, is outside the range of 5. Error message: {1}", e.Message); 
     } 
     catch (Exception e) 
     { 
      Console.WriteLine("out of range error. error message: {0}", e.Message); 
     } 
     Console.ReadLine(); 
    } 
} 
+1

'int.TryParse'不拋出異常,這一翻譯,如果轉換成功,否則返回FALSE – 2014-11-04 12:37:09

+0

你不應該捕獲所有這些異常但在此之前,而不是測試參數,返回TRUE。 – ken2k 2014-11-04 12:37:50

+0

爲什麼你想拋出一個數字低於5的例外?主要是好奇心的 – ZoomVirus 2014-11-04 13:17:12

回答

1
int.TryParse(read, out appel); 

此代碼不會拋出任何異常,這要麼返回True(如果解析成功否則返回false)。 如果您打算拋出一個異常用途:int.Parse

+0

你打我吧:d – Schuere 2014-11-04 12:44:14

+0

這是完美的答案,現在這一切又是有道理的:d – bucket 2014-11-04 12:58:45

0
 bool b = int.TryParse(read, out appel); 
     if(!b) 
      throw new FormatException("{0} is not a valid argument", read); 

 int.Parse(read, out appel); 

這將引發每當輸入了錯誤的值出現FormatException。