在ASP.NET C#中引发异常
时间:2020-03-06 14:19:19 来源:igfitidea点击:
假设" ex"是我们要捕获的异常,只是说" throw;"和" throw ex;"之间有区别吗?
解决方案
throw ex;
将清除堆栈跟踪。除非我们要清除堆栈跟踪,否则请勿执行此操作。只需使用throw;
我们有两个选择权;或者将原始异常作为新异常的内部异常。根据需要。
这是一个简单的代码段,将有助于说明这些差异。区别在于throw ex将重置堆栈跟踪,就像" throw ex;`"行是异常的来源一样。
代码:
using System; namespace StackOverflowMess { class Program { static void TestMethod() { throw new NotImplementedException(); } static void Main(string[] args) { try { //example showing the output of throw ex try { TestMethod(); } catch (Exception ex) { throw ex; } } catch (Exception ex) { Console.WriteLine(ex.ToString()); } Console.WriteLine(); Console.WriteLine(); try { //example showing the output of throw try { TestMethod(); } catch (Exception ex) { throw; } } catch (Exception ex) { Console.WriteLine(ex.ToString()); } Console.ReadLine(); } } }
输出(注意不同的堆栈跟踪):
System.NotImplementedException: The method or operation is not implemented. at StackOverflowMess.Program.Main(String[] args) in Program.cs:line 23 System.NotImplementedException: The method or operation is not implemented. at StackOverflowMess.Program.TestMethod() in Program.cs:line 9 at StackOverflowMess.Program.Main(String[] args) in Program.cs:line 43