我是csharp的初学者,并且刚开始使用它进行编码。我已经编写了代码,但是在catch下方的catch块中有错误(异常)。
static void Main(string[] args)
{
int result;
int x = 5;
int y;
try
{
y = Convert.ToInt32(Console.ReadLine());
result = x / y;
}
catch (Exception)
{
Console.WriteLine("An error occured.");
}
catch (DivideByZeroException error)
{
Console.WriteLine(error.Message);
}
catch (FormatException error)
{
Console.WriteLine(error.Message);
}
finally
{
Console.WriteLine("Please enter valid input!");
}
Console.ReadLine();
}
它出什么问题了?
catch
子句的顺序很重要,因为它们是按顺序检查的。在不太具体的例外之前捕获更具体的例外。看到这个:https : //docs.microsoft.com/zh-cn/dotnet/csharp/language-reference/keywords/try-catch
在您的代码中,将Catch(Exception)块移到finally()块之前,以便最后对其求值。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句