我有以下代码:

con = new iDB2Connection(connectString);
try { con.Open(); }
catch (iDB2ConnectionTimeoutException ex)
{ Console.WriteLine(ex.Message); }
catch (iDB2DCFunctionErrorException ex)
{ Console.WriteLine(ex.Message); }
catch (AccessViolationException ex)
{ Console.WriteLine(ex.Message); }


紧密连接

if (con != null)
{
            try
            {
                Console.WriteLine("CRASH IS AFTER THIS");
                if (con.State != ConnectionState.Closed)
                {
                    con.Close();
                }
            }

            catch (iDB2ConnectionTimeoutException ex)
            {
                Console.WriteLine(ex.Message);
            }
            catch (iDB2DCFunctionErrorException ex)
            {
                Console.WriteLine(ex.Message);
            }
            catch (AccessViolationException ex)
            {
                Console.WriteLine(ex.Message);
            }
            catch (iDB2Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
            finally
            {

            }
        }


但是在运行关闭连接时,我仍然收到此讨厌的消息:

    Unhandled Exception: IBM.Data.DB2.iSeries.iDB2DCFunctionErrorException: An unexp
ected exception occurred.  Type: System.AccessViolationException, Message: Attem
pted to read or write protected memory. This is often an indication that other m
emory is corrupt.. ---> System.AccessViolationException: Attempted to read or wr
ite protected memory. This is often an indication that other memory is corrupt.
   at IBM.Data.DB2.iSeries.CwbDc.DcDnIsAlive(Int32 functionNumber, IntPtr connec
tionHandle, IntPtr nullParm)
   at IBM.Data.DB2.iSeries.MPConnection.IsAlive()
   --- End of inner exception stack trace ---
   at IBM.Data.DB2.iSeries.MPConnection.IsAlive()
   at IBM.Data.DB2.iSeries.MPConnectionManager.GetConnection(iDB2Connection piDB
2Connection)
   at IBM.Data.DB2.iSeries.iDB2Connection.Open()


当我知道iSeries即将停止维护时,我会收到此消息。
我该如何处理以便C#控制台应用程序继续运行?

最佳答案

为什么不将其放在Final块中并仅使用一次try / catch?

con = new iDB2Connection(connectString);

try
{
    con.Open();
}
catch (iDB2ConnectionTimeoutException ex)
{
    Console.WriteLine(ex.Message);
}
catch (iDB2DCFunctionErrorException ex)
{
    Console.WriteLine(ex.Message);
}
catch (AccessViolationException ex)
{
    Console.WriteLine(ex.Message);
}
finally
{
    if (con != null && con.State == ConnectionState.Open)
            con.Close();
}

10-05 22:01