假设我们有这样的结构:
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
Run Code Online (Sandbox Code Playgroud)
我已经看到一些意见认为这样的嵌套Try块是不鼓励的,但我找不到任何具体的原因.
这是坏代码吗?如果是这样,为什么?
我最近遇到了一个程序员编写的代码,他在catch中有一个try-catch语句!
请原谅我无法粘贴实际代码,但他所做的与此类似:
try
{
//ABC Operation
}
catch (ArgumentException ae)
{
try
{
//XYZ Operation
}
catch (IndexOutOfRangeException ioe)
{
//Something
}
}
Run Code Online (Sandbox Code Playgroud)
我个人觉得这是我见过的最差的代码!在1到10的范围内,你认为我应该多久去给他一点心思,还是我过度反应?
编辑:他在捕获中实际做了什么,他正在执行一些操作,这些操作可以/应该在初始尝试失败时完成.我的问题是拥有干净的代码和可维护性.将第一个catch中的异常委托给另一个函数或调用函数就可以,但是添加更多代码可能会或者可能不会将异常抛入第一个catch中,这是我觉得不好的.我试图避免多个堆叠的"if-loop"语句,我发现这同样糟糕.