源地址:http://blog.csdn.net/Joy_Zhao/archive/2006/10/27/1352777.aspx
很多时候,大家当用到向上抛出异常的时候,常常是throw;和throw ex;随便用,从来都没有留意它们之间的区别.今天我才知道,它们之间是有区别的.原文出自:http://mattgollob.blogspot.com/2006/08/throw-vs-throw-ex-heres-difference.html.
大家先看看这个例子.
class Program
{
static void Main(string[] args)
{
ThrowSample ts = new ThrowSample();
try { ts.ThrowMethod(); }
catch(Exception ex)
{
Trace.WriteLine(
"Exception caught from ThrowMethod:");
Trace.WriteLine(ex.ToString());
}
try { ts.ThrowExMethod2(); }
catch (Exception ex)
{
Trace.WriteLine( "Exception caught from ThrowExMethod:");
Trace.WriteLine(ex.ToString());
}
}
下面是ThrowSample类:
class ThrowSample
{
public ThrowSample()
{
}
private void ExceptionMethod()
{
throw;
}
public void ThrowExMethod()
{
try { this.ExceptionMethod(); }
catch (Exception ex)
{
// Log the exception
throw;
}
}
public void ThrowExMethod2()
{
try { this.ExceptionMethod(); }
catch (Exception ex)
{
// Log the exception
throw ex;
}
}
}大家可以看到它的两个方法ThrowMethod()与ThrowMethod2()之间的区别,一个是用了throw,另外一个则是用throw ex,好,执行第一段代码,输出结果如下:
Exception caught from ThrowMethod:
System.Exception: DOH!
at ThrowSample.ThrowSample.ExceptionMethod() in
C:ThrowSampleProgram.cs:line 55
at ThrowSample.ThrowSample.ThrowMethod() in
C:ThrowSampleProgram.cs:line 38
at ThrowSample.Program.Main(String[] args) in
C:ThrowSampleProgram.cs:line 14
Exception caught from ThrowExMethod2:
System.Exception: DOH!
at ThrowSample.ThrowSample.ThrowExMethod2() in
C:ThrowSampleProgram.cs:line 48
at ThrowSample.Program.Main(String[] args) in
C:ThrowSampleProgram.cs:line 21
从结果我们不难发现,前者比后者多了一条信息,而这条信息正是发生异常的根本来源的说明,而后者显然漏掉了这一关键信息.如果我们采用后者,那么我们势必会很难发现问题的来源,特别是当ThrowExMethod方法非常复杂的时候.现在让我们做个假设,如果从ThrowExMethod到ExceptionMethod之间还夹杂了一系列的方法调用,每一个方法都往上抛出一个新的异常(throw ex;)那我们将更加困难的知道异常真正发生的地方,所以明白它们之间的区别非常重要.
尽管如此,也不是说throw ex;就是一无是处,就是完全不好的,你可以在当你需要向你捕获的异常中添加一些信息的时候,可以新建一个异常,然后初始化原始异常为其内部异常,比如:
public void ThrowExMethod2()
...{
try ...{ this.ExceptionMethod(); }
catch (Exception ex)
...{
// Log the exception
throw new ApplicationException("Uh-oh!", ex);
}
}那么异常的堆栈信息将会被正确保存:
Exception caught from ThrowExMethod:
System.ApplicationException: Uh-oh! ---> System.Exception: DOH!
at ThrowSample.ThrowSample.ExceptionMethod() in
C:ThrowSampleProgram.cs:line 65
at ThrowSample.ThrowSample.ThrowExMethod2() in
C:ThrowSampleProgram.cs:line 54
--- End of inner exception stack trace ---
at ThrowSample.ThrowSample.ThrowExMethod2() in
C:ThrowSampleProgram.cs:line 58
at ThrowSample.Program.Main(String[] args) in
C:ThrowSampleProgram.cs:line 21
头一次翻译别人的文章,力求把文章意思弄清楚,没有可以去字字句句去对照.
本文来自CSDN博客,转载请标明出处:http://blog.csdn.net/Joy_Zhao/archive/2006/10/27/1352777.aspx