gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 19:00:44 24 4
gpt4 key购买 nike

如何在 .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。

如何正确处理内部异常?

最佳答案

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

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

关于c# - 如何在 .NET 中捕获内部异常?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1558189/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com