简而言之,是的,有更好的方法来处理它。它的“如何”取决于你。
C# 中的异常处理从最具体的异常类型到最不具体的. 此外,您不仅限于使用一个catch
块。你可以有很多。
举个例子:
try
{
// Perform some actions here.
}
catch (Exception exc) // This is the most generic exception type.
{
// Handle your exception here.
}
上面的代码是你已经拥有的。要显示您可能想要的示例:
try
{
// Perform some actions here.
}
catch (SqlException sqlExc) // This is a more specific exception type.
{
// Handle your exception here.
}
catch (Exception exc) // This is the most generic exception type.
{
// Handle your exception here.
}
在 Visual Studio 中,可以通过按 CTRL+ALT+E 查看(大多数)异常列表。