如何在C#中获取异常类型

Fra*_*dal 9 c# exception-handling

我想检查服务器是否无法访问,如果无法访问,我想在我的登录页面上打印一条友好的消息.就像当用户输入其凭证并在我得到的异常时

建立与SQL Server的连接时发生与网络相关或特定于实例的错误.服务器未找到或无法访问.验证实例名称是否正确,以及SQL Server是否配置为允许远程连接.(提供者:命名管道提供程序,错误:40 - 无法打开与SQL Server的连接)

这个例外.那么我应该怎样在发生哪个异常时才能显示消息?

小智 23

我知道这是一篇较旧的帖子,但是如果您要以相同的方式处理所有异常和/或使用错误报告或类似信息(而不是通知用户具体细节),您可以使用以下内容.

try
{
    //do something here
}
catch(Exception ex)
{
    MessageBox.Show(ex.GetType().ToString()); //will print System.NullReferenceException for example
}
Run Code Online (Sandbox Code Playgroud)


小智 13

您需要在代码时知道期望的异常,以便相应地捕获它们.正如Dimitrov所说,当与SQL服务器的连接失败时会抛出SQLException,因此特别注意这是一个很好的策略.

您希望按顺序捕获各种异常,如下所示:

try 
{
    //some code
}
catch(TypeOfException exOne) 
{
    //handle TypeOfException someway
}
catch (OtherTypeOfException exTwo) 
{
    //handle OtherTypeOfException some other way
}
catch (Exception ex) 
{
    //handle unknown exceptions in a general way
}
finally 
{
    //any required cleanup code goes here
}
Run Code Online (Sandbox Code Playgroud)

尝试将最不寻常的例外放在最顶层,沿着列表向更常见的例外方向发展.catch顺序是顺序的 - 如果你将catch(Exception)放在顶部,它将始终捕获该行,无论你在其下面编码什么异常.


Dar*_*rov 7

您可以尝试捕获SQLException:

try 
{
    // Try sending a sample SQL query
} 
catch (SQLException ex) 
{
    // Print error message
}
Run Code Online (Sandbox Code Playgroud)


Baz*_*nga 6

您可以使用与用于检查父类是否为类型子类的相同方法来完成

 obj is NotImplementedException
Run Code Online (Sandbox Code Playgroud)

你的obj是Exception类型的所有异常的父类.

或者如果您想稍后使用异常对象,则可以使用:

var niException=obj as NotImplementedException
if(niException==null)  //will be null when object is not of type NotImplementedException
return;
Run Code Online (Sandbox Code Playgroud)

当您有一个用于处理异常的集中类并且不想添加多个catch语句时,此逻辑特别有用

希望这可以帮助.