2015-08-30 129 views
-2

我正在使用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

其他信息:无连接可以作出,因为目标机器积极地拒绝它

回答

2

这是投掷SocketException。你正在赶上NpgsqlException。如果您为SocketException添加二级渔获物,那么它会被捕获。

+0

谢谢。我很想知道你是怎么知道SocketException是抛出的异常的,因为这会帮助我找到未来的方向。 – docesam

+0

这是您发布的确切错误消息。 “未处理的异常被抛出。”这是它的异常类型,如果你没有捕获它或继承它的东西(即只是一个普通的catch(Exception ex)),它仍然会崩溃。我认为你也可以在没有catch指定一个特定的类型,但是这通常不是一个好主意,但是我可能会把它与Java混合起来,我忘记了 – sab669

+0

谢谢你。 – docesam

0

你的代码是正确的,但是对于错误的连接字符串NOTSupportedException或IoException已被抛出,这将抛出一般异常类,数据库关闭或不存在错误获取显示“数据库不存在”与NPGSqlException类。 检查一般异常类。