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

roy*_*yco 2 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
Run Code Online (Sandbox Code Playgroud)

上面的伪代码失败了'Fails here,ex2永远不会被我的代码处理.

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

Joe*_*orn 10

您当前代码不起作用的原因是,一旦您进入catch部分,您就已经离开了try块.相反,这样做:

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
Run Code Online (Sandbox Code Playgroud)

或者像这样:

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
Run Code Online (Sandbox Code Playgroud)