简体   繁体   中英

NpgsqlException is not caught in catch block

I am connecting to local postgresql instance like this:

        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(). 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

Try this instead. Your try-catch block is outside of the 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) {
            ...
        }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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