【问题标题】:Catch oledb Exception with a specific error code使用特定错误代码捕获 oledb 异常
【发布时间】:2012-12-29 00:56:45
【问题描述】:

我正在尝试捕获重复的密钥违规行为。我可以在 Intellisense 弹出窗口中看到 System.OleDB.OleDBException,但内部异常为空。如何访问 System.OleDB.OleDBException 中的错误代码?

格雷格

try 
{
    MyData.ConExec(sSQL);
}
    catch (Exception ex)
{
OleDbException innerException = ex.InnerException as OleDbException;
if (innerException.ErrorCode == -2147217873)
{
    // handle exception here..
}
else
{
    throw;
}
}

【问题讨论】:

  • 尝试捕获 OleDBException 而不是捕获一般异常。
  • 以上代码在innerException.ErrorCode上的引用可能为空

标签: c# exception try-catch oledb


【解决方案1】:

不要声明异常的实例。如果你这样做,它肯定会返回空。

try
{
    MyData.ConExec(sSQL);
}
catch (OleDbException ex)
{
    // handle excpetion here...

    if (ex.ErrorCode == -2147217873)
    {

    }
}
catch (Exception e)
{
    // if other exception will occur
}

【讨论】:

  • 明白了。谢谢。男孩,我以前来过这里,但我已经很久没有需要捕获特定错误了。再次感谢。格雷格
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-03-27
  • 1970-01-01
  • 2015-04-16
  • 2012-11-11
  • 2015-06-11
  • 1970-01-01
相关资源
最近更新 更多