简体   繁体   English

NpgsqlException 未在 catch 块中捕获

[英]NpgsqlException is not caught in catch block

I am connecting to local postgresql instance like this:我像这样连接到本地 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)
        {
           ...
        }

Then for testing purposes I stop database server from Task Manager=>Services and when I try to connect of course get exception : "No connection could be made because the target machine actively refused it " But interesting part is that this exception is not caught by the catch block but simply crashes my program at line connection.Open().然后出于测试目的,我从任务管理器 => 服务停止数据库服务器,当我尝试连接时当然会得到异常: “无法建立连接,因为目标机器主动拒绝它”但有趣的部分是这个异常没有被捕获catch 块,但只是在行 connection.Open() 处使我的程序崩溃。 Can anyone explain, why is it so?谁能解释一下,为什么会这样?

I recommend u to change我建议你改变

catch (NpgsqlException ex)
    {
       ...
    }

to

catch (Exception ex)
    {
       ...
    }

and see actual type of exception并查看实际的异常类型

it can be "PostgresException" https://www.npgsql.org/doc/api/Npgsql.PostgresException.html它可以是“PostgresException” https://www.npgsql.org/doc/api/Npgsql.PostgresException.html

Try this instead.试试这个。 Your try-catch block is outside of the using NpsqlConnection.您的 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) {
            ...
        }
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM