C# 在catch块中未捕获NpgsqlException

C# 在catch块中未捕获NpgsqlException,c#,postgresql,exception,npgsql,C#,Postgresql,Exception,Npgsql,我正在连接本地postgresql实例,如下所示: try { using (var connection = new NpgsqlConnection(connectionString)) { using (var command = new NpgsqlCommand("loadProjects", connection)) {

我正在连接本地postgresql实例,如下所示:

        try
        {
            using (var connection = new NpgsqlConnection(connectionString))
            {
                using (var command = new NpgsqlCommand("loadProjects", connection))
                {
                    command.CommandType = CommandType.StoredProcedure;
                    connection.Open();

                    using (NpgsqlDataReader dataReader = command.ExecuteReader())
                    {
                       ...
                    }
                }
            }
        }
        catch (NpgsqlException ex)
        {
           ...
        }
然后出于测试目的,我从TaskManager=>Services停止数据库服务器,当我尝试连接时,当然会出现异常:“无法建立连接,因为目标计算机主动拒绝了它。”
“但有趣的是,这个异常并没有被catch块捕获,只是在line connection.Open()上使我的程序崩溃。有人能解释一下,为什么会这样吗?

我建议你改变一下

catch (NpgsqlException ex)
    {
       ...
    }

并查看异常的实际类型


可以是“PostgresException”

试试这个。您的try-catch块位于using-NpsqlConnection之外

using (var connection = new NpgsqlConnection (connectionString)) {
    using (var command = new NpgsqlCommand ("loadProjects", connection)) {
        command.CommandType = CommandType.StoredProcedure;

        try {
            connection.Open ();

            using (NpgsqlDataReader dataReader = command.ExecuteReader ()) {
                ...
            }

        } catch (NpgsqlException ex) {
            ...
        }
    }
}

您确定这是实际引发的异常吗?将代码更改为
catch(Exception ex)
,然后重新运行它并查看实际的类型。“有人能解释一下,为什么会这样吗?”最简单的解释是,不会抛出
NpgsqlException
,而是从另一种类型抛出一个异常。我见过很多情况下,using处理异常。在using中放置两个异常处理程序,看看是否捕获了异常。这也是我的假设。连接器类有一个套接字字段=>
Socket\u Socket=default基本上建立了连接。这会引发异常。您应该始终拥有一个通用的
catch(Exception ex)
子句作为最后一个catch,因为您永远不知道异常可能发生的深度。文档不会告诉您它可能抛出的所有异常:)@Mong-Zhu谢谢!我想如果你把这篇文章作为一个答案,它也可能对其他人有用!为什么这会对@niks的方法产生影响?我已经做了这些更改,我得到的是“Message=无法建立连接,因为目标机器主动拒绝了它”和“Source=Npgsql”NpgsqlException不应该捕获这种类型的异常吗?@niks不查看消息look at
string typeName=ex.GetType().ToString()
using (var connection = new NpgsqlConnection (connectionString)) {
    using (var command = new NpgsqlCommand ("loadProjects", connection)) {
        command.CommandType = CommandType.StoredProcedure;

        try {
            connection.Open ();

            using (NpgsqlDataReader dataReader = command.ExecuteReader ()) {
                ...
            }

        } catch (NpgsqlException ex) {
            ...
        }
    }
}