我正在使用Npgsql测试postgreSQL连接。我想知道当我犯错时会发生什么,例如错误的连接字符串,数据库已关闭......等等所以我制作了这个简单的程序来测试Npgsqlexceptions但是try语句没有捕获异常:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Npgsql;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
NpgsqlConnection conn = new NpgsqlConnection("Server=127.0.0.1;Port=5432;User Id=postgres;Password=knbvbnv;Database=testdb;");
try
{
conn.Open();
}
catch (NpgsqlException ee)
{
Console.WriteLine("======== ee.Code ===============");
Console.WriteLine(ee.Code);
Console.WriteLine("======== ee.ColumnName ===============");
Console.WriteLine(ee.ColumnName);
Console.WriteLine("======== ee.ConstraintName ===============");
Console.WriteLine(ee.ConstraintName);
Console.WriteLine("======== ee.DataTypeName ===============");
Console.WriteLine(ee.DataTypeName);
Console.WriteLine("======== Detail ===============");
Console.WriteLine(ee.Detail);
Console.WriteLine("======== ErrorCode ===============");
Console.WriteLine(ee.ErrorCode);
Console.WriteLine("======== HResult ===============");
Console.WriteLine(ee.HResult);
Console.WriteLine("======== InternalQuery ===============");
Console.WriteLine(ee.InternalQuery);
Console.WriteLine("======== Message ===============");
Console.WriteLine(ee.Message);
Console.WriteLine("======== MessageText ===============");
Console.WriteLine(ee.MessageText);
Console.WriteLine("======== Position ===============");
Console.WriteLine(ee.Position);
Console.WriteLine("======== Severity ===============");
Console.WriteLine(ee.Severity);
Console.WriteLine("======== TargetSite ===============");
Console.WriteLine(ee.TargetSite);
Console.WriteLine("======== Where ===============");
Console.WriteLine(ee.Where);
Console.WriteLine("======== ===============");
}
}
}
}
为什么尝试不会发现错误?
Visual Studio中的异常是: 类型为#System.SNet.Sockets.SocketException'的未处理异常发生在Npgsql.dll
中附加信息:由于目标计算机主动拒绝连接,因此无法建立连接
答案 0 :(得分:2)
它正在抛出一个class Truth:
def __init__(self, truth):
self.truth = truth
def __nonzero__(self):
return self.truth
t = Truth(True)
f = Truth(False)
print bool(t and t)
print bool(t and f)
print bool(f and f)
。你正在追赶SocketException
。如果为NpgsqlException
添加辅助捕获,那么它将会捕获。
答案 1 :(得分:0)
您的代码是正确的,但是对于错误的连接字符串NOTSupportedException或IoException已被抛出,它将捕获一般异常类,对于数据库已关闭或不存在错误,将显示错误"数据库不存在"使用NPGSqlException类。 检查一般异常类。