在C#中使用try-catch块的正确方法是什么

mjs*_*jsr 1 c# exception-handling exception try-catch

我想知道您对应用try-catch块捕获异常的正确方法的看法.

假设我有4级层次结构方法,这些方法是这样的:

method1(){
   method2(){
       method3(){
          method4()
       }
       morecode that depend of what happend in method3
   }
   morecode that depend of what happend in method2
}
Run Code Online (Sandbox Code Playgroud)

所以我所做的是从内到外包含将要呈现异常的可能方法,因为我的代码依赖于在这些方法中发生的不同级别,我使用"throw"句子传播异常以避免这些代码产生崩溃.

method1(){
   try
   method2(){
       try
       method3(){
          try
          method4()
          catch
          throw
       }
       catch
       throw
       morecode that depend of what happend in method3
   }
   catch
   return
   morecode that depend of what happend in method2
}
Run Code Online (Sandbox Code Playgroud)

这是正确的方法吗?或者我正在使用"抛出"句子?

Ode*_*ded 6

如果您要做的catch就是重新投掷,请不要打扰try.

异常会冒出来,所以没有必要像这样捕获和重新抛出 - 你仍然会获得正确的堆栈跟踪.