我正在使用Npgsql测试postgreSQL连接。我想知道发生了什么,当我犯了一个错误,例如错误的连接字符串,数据库关闭....等等,所以我做了这个简单的程序来测试Npgsqlexceptions,但尝试声明不捕捉异常:PostgreSQL的try-catch没有捕获异常
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.Net.Sockets.SocketException”未处理的异常发生在Npgsql.dll
其他信息:无连接可以作出,因为目标机器积极地拒绝它
谢谢。我很想知道你是怎么知道SocketException是抛出的异常的,因为这会帮助我找到未来的方向。 – docesam
这是您发布的确切错误消息。 “未处理的异常被抛出。”这是它的异常类型,如果你没有捕获它或继承它的东西(即只是一个普通的catch(Exception ex)),它仍然会崩溃。我认为你也可以在没有catch指定一个特定的类型,但是这通常不是一个好主意,但是我可能会把它与Java混合起来,我忘记了 –
sab669
谢谢你。 – docesam