Difference: throw or throw ex?
Difference: throw or throw ex?
主要區別在于throw出的堆棧詳細程度。
throw ex只是拋出在當前代碼處的錯誤。
throw 能夠更進一步,拋出內部調用的具體錯誤。
Just for demonstrating, if you have classes in C#?as follows:
| using System;namespace WindowsApplication2 {public class Class1{public static void DoSomething(){try{Class2.DoSomething(); }catch(Exception ex){throw ex;}}}public class Class2{public static void DoSomething(){try{Class3.DoSomething(); }catch(Exception ex){throw ex;}}}public class Class3{public static void DoSomething(){try{int divider=0;int number=5/divider;}catch(Exception ex){throw ex;}}} } |
| And you call: Class1.DoSomething(); What's the difference if you rethrow the exception using plain 'throw;' or 'throw ex;'? ? ANSWER: If you use "throw ex;", The stack trace is something like: System.DivideByZeroException: Attempted to divide by zero. ? |
| ? |
| But if you use just 'throw' instead of 'throw ex' to rethrow the same?exception, that is: public class Class3{public static void DoSomething(){try{int divider=0;int number=5/divider;}catch{throw ;}}}
System.DivideByZeroException: Attempted to divide by zero. See the difference??BTW: This concerns both C# and VB. VB docs state that in "Throw?expression" the?expression?would be required. This is not completely true, you can use just "Throw" in VB?to rethrow the same?exception. C# docs do tell that in "throw?expression" the?expression?"is omitted when rethrowing the current exception object in a catch clause". |
本文轉自cnn23711151CTO博客,原文鏈接:http://blog.51cto.com/cnn237111/508446?,如需轉載請自行聯系原作者
創作挑戰賽新人創作獎勵來咯,堅持創作打卡瓜分現金大獎
總結
以上是生活随笔為你收集整理的Difference: throw or throw ex?的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 数据库的事务级别介绍与操作
- 下一篇: 用css美化的简易计算器 |完整代码及注