我想测试捕获格式异常,但如果我尝试输入任何单词,程序会崩溃。如何让我的程序捕获异常而不会崩溃?
string words;
int[] number;
int i = 0;
while (true)
{
Console.WriteLine("How many numbers would you like to enter? ");
words = Console.ReadLine();
if (isInteger(words))
{
number = new int[Convert.ToInt32(words)];
Console.WriteLine("Please enter your numbers: ");
for (i = 0; i < number.Length; ++i)
{
number[i] = Convert.ToInt32(Console.ReadLine());
isInteger(words);
}
}
}
isInteger
方法:
private static bool isInteger(string words)
{
try
{
return true;
}
catch (FormatException)
{
return false;
}
}
答案 0 :(得分:0)
如果要捕获对Convert
Convert.ToInt32(words)
或Convert.ToInt32(Console.ReadLine())
的调用引发的异常,则需要将它们包装在try catch块中。任何catch只处理前一次try中发生的异常。所以,例如
try
{
number = new int[Convert.ToInt32(words);
}
catch (FormatException ex)
{
// Do something here ex is needed if you want to look at the exception
}
或者你可以将它全部包装在一个试试中
try
{
number = new int[Convert.ToInt32(words);
Console.WriteLine("Please enter your numbers: ");
for (i = 0; i < number.Length; ++i)
{
number[i] = Convert.ToInt32(Console.ReadLine());
isInteger(words);
}
}
catch (FormatException ex)
{
// Do something here ex is needed if you want to look at the exception
}
isInteger
将永远不会有异常处理,因为它所做的只是返回true,它永远不会被处理。如果要处理函数中的异常,则该函数必须进行除catch或在catch块中调用的调用。