gpt4 book ai didi

.net - 嵌套 Try/Catch block 是一个坏主意吗?

转载 作者:行者123 更新时间:2023-12-02 17:29:43 58 4
gpt4 key购买 nike

假设我们有这样的结构:

Try
' Outer try code, that can fail with more generic conditions,
' that I know less about and might not be able to handle

Try
' Inner try code, that can fail with more specific conditions,
' that I probably know more about, and are likely to handle appropriately
Catch innerEx as Exception
' Handle the inner exception
End Try

Catch outerEx as Exception
' Handle outer exception
End Try

我看到一些观点认为不鼓励像这样嵌套 Try block ,但我找不到任何具体原因。

这是错误的代码吗?如果是这样,为什么?

最佳答案

在某些情况下它们是个好主意,例如一个 try/catch 用于整个方法,另一个在循环内,因为您想要处理异常并继续处理集合的其余部分。

实际上,这样做的唯一原因是如果您想跳过出错的位并继续,而不是展开堆栈并丢失上下文。在编辑器中打开多个文件就是一个示例。

也就是说,异常应该(顾名思义)是异常的。程序应该处理它们,但尽量避免将它们作为正常执行流程的一部分。对于大多数语言来说,它们的计算成本很高(Python 是一个值得注意的异常(exception))。

另一种有用的技术是捕获特定的异常类型...

Try
'Some code to read from a file

Catch ex as IOException
'Handle file access issues (possibly silently depending on usage)
Catch ex as Exception
' Handle all other exceptions.
' If you've got a handler further up, just omit this Catch and let the
' exception propagate
Throw
End Try

我们还在错误处理例程中使用嵌套的 try/catch...

    Try
Dim Message = String.Format("...", )
Try
'Log to database
Catch ex As Exception
'Do nothing
End Try

Try
'Log to file
Catch ex As Exception
'Do nothing
End Try
Catch ex As Exception
'Give up and go home
End Try

关于.net - 嵌套 Try/Catch block 是一个坏主意吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4799758/

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