如何在.NET中捕获内部异常?

时间:2009-10-13 04:29:09

标签: c# vb.net

如何在.NET中捕获内部异常?我需要检查2个数据库以获取记录。如果找不到记录,数据库代码会抛出异常,因此我想检查第二个数据库:

Try
     # Code to look in database 1
Catch ex as DataServiceQueryException
     Try
          # Code to look in database 2
     Catch ex2 as DataServiceQueryException
          throw New DataServiceQueryException(ex.Message, ex2) # Fails here
     End Try
Catch ex as Exception # Why doesn't ex2 land here?
   # Tell user that data was not found in either database
End Try

上面的伪代码在'Fails here处失败,而ex2从未由我的代码处理。

我该如何正确处理内部异常?

5 个答案:

答案 0 :(得分:10)

您当前代码无效的原因是,一旦您进入catch部分,您已经尝试块。相反,这样做:

Try
   ''# Check Database 1
Catch
    Try
        ''# Check Database 2
    Catch
         ''# Tell the user that data was not found in either database
    End Try
End Try

或者像这样:

Dim FoundFlag as Boolean = False
Try
    ''# Check Database 1
    FoundFlag = True
    ''# Best if you can just return "False" and avoid the exception altogether
Catch
End Try

If Not FoundFlag Then
    Try
        ''# Check Database 2
        FoundFlag = True
    Catch
    End Try
End If

If Not FoundFlag Then
     ''# Tell the user that data was not found in any database
End If

答案 1 :(得分:3)

根据定义,内部异常已经被处理并重新打包为另一个例外。您必须处理外部异常,然后在必要时/适当处理外部异常的catch块中的内部异常。

答案 2 :(得分:1)

首先,如果你正在使用try / catch,你应该最终要清理资源。话虽这么说,嵌套try / catch阻止我们通常代码气味。你必须这样实现吗?为什么服务器会失败?为什么数据层不能传递状态消息?例外情况应该是“例外”。

如果你必须使用例外,“Joel Coehoorn”的方式似乎很好。

答案 3 :(得分:0)

我会说,基于伪代码,这是因为你在第7行抛出的异常位于第3行的“try”块内,所以第9行的“catch”根本不适用。

编辑:乔尔说的话。

答案 4 :(得分:0)

我同意Joel,我希望进一步建议你坐下来决定你真正希望发生以下哪种情况,然后进行相应的编码。

案例A. 如果db1中存在record11 然后检查db2中是否存在record22

try{
  getRecord11;

  try
  {
    getRecord22;
  }
  catch ex22
  {
    saySorry2;
  }
}
catch ex11
{
  saySorry1;
}

案例B. 如果db1中不存在record11 然后检查db2中是否存在record22

try{
  getRecord11;
}
catch ex11
{
  saySorry1;

  try
  {
    getRecord22;
  }
  catch ex22
  {
    saySorry2;
  }
}
案例C. 从db1获取记录11。 无论db1结果如何,都要从db2获取record22。

try{
  getRecord11;
}
catch ex11
{
  saySorry1;
}

try
{
  getRecord22;
}
catch ex22
{
  saySorry2;
}
相关问题