有些帖子问这两者之间已经有什么区别。 (为什么我什至不得不提这个…)
但是我的问题有所不同,在另一种 类似于神的 错误处理方法中,我称其为“ throw ex” 。
public class Program { public static void Main(string[] args) { try { // something } catch (Exception ex) { HandleException(ex); } } private static void HandleException(Exception ex) { if (ex is ThreadAbortException) { // ignore then, return; } if (ex is ArgumentOutOfRangeException) { // Log then, throw ex; } if (ex is InvalidOperationException) { // Show message then, throw ex; } // and so on. } }
如果try & catch在中使用Main,那么我将使用throw;该错误。但是在上面简化的代码中,所有异常都会通过HandleException
try & catch
Main
throw;
HandleException
是否throw ex;与调用同样的效果throw里面调用时HandleException?
throw ex;
throw
是,有一点不同;
throw ex
throw 不会-原罪犯将得到保留。
static void Main(string[] args)
{ try { Method2(); } catch (Exception ex) { Console.Write(ex.StackTrace.ToString()); Console.ReadKey(); } }
private static void Method2() { try { Method1(); } catch (Exception ex) { //throw ex resets the stack trace Coming from Method 1 and propogates it to the caller(Main) throw ex; } }
private static void Method1() { try { throw new Exception(“Inside Method1”); } catch (Exception) { throw; } }