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

问题描述 投票:9回答:8

我想检查服务器是否不可访问,以及服务器是否不可访问,我想在登录页面上打印一条友好的消息。就像当用户输入其凭据时,我得到

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

此例外。那么,当发生哪种异常时我应该如何显示消息呢?

c# exception-handling
8个回答
7
投票

您可以尝试捕获SQLException

try 
{
    // Try sending a sample SQL query
} 
catch (SQLException ex) 
{
    // Print error message
}

24
投票

我知道这是一篇较旧的文章,但是如果您将以相同的方式处理所有异常和/或将这些信息用于错误报告或类似的内容(而不是通知用户详细信息),则可以使用以下内容。

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

13
投票

您需要在代码时知道预期的异常,以便相应地捕获它们。正如Dimitrov所述,当与SQL Server的连接失败时,将引发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
}

[尝试将最不寻常的例外放在首位,将列表从最常见的例外中移出。 catch序列是顺序的-如果将catch(Exception)放在顶部,则无论您在其下面编写什么异常,它都将始终在该行上捕获。]


6
投票

您可以使用与检查父类是否属于子类类型相同的方法,这是使用]完成的。

 obj is NotImplementedException

2
投票
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 }

0
投票

您必须捕获例外:


0
投票
try
{
    // Your code
}
catch (SQLException ex)
{
    Response.Write(ex.Message);    // For web apps
    Console.WriteLine(ex.Message); // For Windows apps
}

-1
投票

我认为,解决方法是:

© www.soinside.com 2019 - 2024. All rights reserved.