嵌套的try-catch:为外部try catch循环抛出异常

时间:2019-10-18 17:48:58

标签: .net vb.net try-catch

我定义了2个自定义例外,例如

Public Class SkipException
   Inherits System.ApplicationException
End Class

Public Class NoRecordFoundException
   Inherits System.ApplicationException
End Class

在我的代码中,场景是 1.数据导致一般异常 2.我没有数据 3.我已经处理过的异常

Try
'Some code here
    Try
       ''Do some code
       ''Cant find the record
       If i = 0 then
           Throw NoRecordFoundException
       End if 
    Catch ex as Exception

    End Try

    Try
        ''Cant do nothing so just skip
        If CantDoNothing then
           Throw SkipException
        End if
    Catch ex as Exception

    End Try
Catch SkipException
  ''Some code here
Catch NoRecordFoundException
  '' some code here
Catch ex as Exception
   ''Handle regular exception
End Try

那么这行得通吗?例外会转到外部处理而不是内部捕获吗?

现在,我重新抛出异常以使其正常工作。

1 个答案:

答案 0 :(得分:1)

只需处理特定的异常并重新抛出。以下Catch ex as Exception将忽略之前捕获的异常。

Try
    Try
        Throw New NoRecordFoundException()
    Catch ex As NoRecordFoundException
        Throw
    Catch ex As Exception
        ' nothing happens here
    End Try
Catch ex As NoRecordFoundException
    ' handled here
Catch ex As Exception
    ' nothing happens here
End Try