Throw 和 Throw ex 抛出异常的区别一般体现在多重方法try/catch/finally的情况,Throw 可以抛出最深层次方法的异常,Throw ex 则是不行。看看如下例子:
1.Throw 抛出异常
using System; namespace ThrowTest { class Program { static void Main(string[] args) { try { ***ThrowOne();*** } catch (Exception ex) { Console.WriteLine(ex.StackTrace.ToString()); } Console.ReadKey(); } static void ThrowOne() { try { ThrowTwo(); } catch (Exception ex) { ***throw;*** } } static void ThrowTwo() { try { throw new Exception("来自方法2的异常"); } catch (Exception ex) { ***throw;*** } } } }
2.Throw ex 抛出异常
using System; namespace ThrowTest { class Program { static void Main(string[] args) { try { ***ThrowOne();*** } catch (Exception ex) { Console.WriteLine(ex.StackTrace.ToString()); } Console.ReadKey(); } static void ThrowOne() { try { ThrowTwo(); } catch (Exception ex) { ***throw ex;*** } } static void ThrowTwo() { try { throw new Exception("来自方法2的异常"); } catch (Exception ex) { throw ex; } } } }
Throw 和 Throw ex 抛出异常如上面两段代码[斜体加粗部分],对比可以知道:
Throw 段代码:出现三个加粗,表示有三个地方抛出异常,可以把最深层次的异常抛出;
Throw ex 段代码:出现二个加粗,表示有二个地方抛出异常,不能把最深层次的异常抛出;
两个异常方法
①: throwMethodOne exist throw
②: throwMethodTwo exit throw ex
- ①调用②能抛出①②的异常,
- ①调用②不能抛出①的异常,只能抛出②的异常。