我有包括使用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();
}
}
'int.TryParse'不拋出異常,這一翻譯,如果轉換成功,否則返回FALSE – 2014-11-04 12:37:09
你不應該捕獲所有這些異常但在此之前,而不是測試參數,返回TRUE。 – ken2k 2014-11-04 12:37:50
爲什麼你想拋出一個數字低於5的例外?主要是好奇心的 – ZoomVirus 2014-11-04 13:17:12