C# 如何在.NET中捕获内部异常?
如何在.NET中捕获内部异常?我需要检查两个数据库的记录。如果未找到记录,数据库代码将引发异常,因此我想检查第二个数据库:C# 如何在.NET中捕获内部异常?,c#,vb.net,C#,Vb.net,如何在.NET中捕获内部异常?我需要检查两个数据库的记录。如果未找到记录,数据库代码将引发异常,因此我想检查第二个数据库: Try # Code to look in database 1 Catch ex as DataServiceQueryException Try # Code to look in database 2 Catch ex2 as DataServiceQueryException throw New
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
上面的伪代码在处失败,在这里失败,我的代码从不处理ex2
如何正确处理内部异常?根据定义,内部异常已被处理并重新打包为另一个异常。您必须处理外部异常,然后在必要/适当的情况下处理外部异常的catch块中的内部异常。当前代码无法工作的原因是,一旦进入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
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
或者像这样:
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
根据伪代码,我会说,这是因为您在第7行抛出的异常在第3行周围的“try”块中,所以第9行的“catch”根本不适用
编辑:Joel所说的。首先,如果您使用的是try/catch,您可能需要一个finally来清理资源。也就是说,嵌套的try/catch通常会让我们感觉到代码的味道。你必须这样实施吗?为什么服务器会出故障?为什么数据层不能传递状态消息?例外情况应该是“例外”
如果必须使用异常,“Joel Coehoorn”的方法似乎很好。我同意Joel的观点,我希望进一步建议您坐下来决定您真正希望发生以下哪种情况,然后相应地编写代码
案例A。
如果db1中存在record11
然后检查db2中是否存在record22
try{
getRecord11;
try
{
getRecord22;
}
catch ex22
{
saySorry2;
}
}
catch ex11
{
saySorry1;
}
try{
getRecord11;
}
catch ex11
{
saySorry1;
try
{
getRecord22;
}
catch ex22
{
saySorry2;
}
}
案例B。
如果db1中不存在record11
然后检查db2中是否存在record22
try{
getRecord11;
try
{
getRecord22;
}
catch ex22
{
saySorry2;
}
}
catch ex11
{
saySorry1;
}
try{
getRecord11;
}
catch ex11
{
saySorry1;
try
{
getRecord22;
}
catch ex22
{
saySorry2;
}
}
案例C。
从db1获取record11。
不管db1结果如何,从db2获取record22
try{
getRecord11;
}
catch ex11
{
saySorry1;
}
try
{
getRecord22;
}
catch ex22
{
saySorry2;
}
嗯,这就是我试图用Catch ex作为异常来做的事情。我以为内部异常会被外部的Catch
捕获。谢谢。第一个示例非常有效。不幸的是,我无法避免这个例外。“数据库”是一个Azure REST服务,如果找不到记录,它将返回404。这会导致REST包装器抛出异常。我想我根本不需要抛出内部异常。谢谢你的想法。不幸的是,我不知道如何使用异常。在Azure表中,如果您搜索一个唯一的实体,但未找到该实体,则会引发异常。也就是说,如果您搜索特定的PrimaryKey和RowKey组合,您将抛出DataServiceQueryException。谢谢您的帖子。除了我的场景是“从db1获取record11。如果失败,则从db2获取record11。如果失败,则说抱歉”,我基本上是案例B。谢谢你的例子。