看了 《Visual C# Best Practices: What’s Wrong With This Code?》的PPT,其中第一节
对于抛出异常有两种方式,第一种为
public void ThrowException()
{
try
{
throw new Exception("exception");
}
catch(Exception e)
{
throw e;
}
}
第二种为
public void ThrowException()
{
try
{
throw new Exception("exception");
}
catch(Exception e)
{
throw ;
}
}
对于这个,究竟有什么不同了,我写了个小程序车是他们的不同。如果使用Throw e,那么报错的Track
报告的位置就是 throw e 的位置,如果使用throw,那么报错的位置是产生这个异常的真实位置。也就是说throw
更正确
测试代码如下:
using System;
using NUnit.Framework;
namespace TestNunit
{
/// <summary>
/// TestContainer 的摘要说明。
/// </summary>
[TestFixture]
public class ttt
{
[Test]
public void ThrowE()
{
aClass a=new aClass();
a.ThrowException2();
}
[Test]
public void Throw()
{
aClass a=new aClass();
a.ThrowException1();
}
}
public class exceptionClass
{
public static void throwException()
{
//当使用TrhowException1方法的时候,throw的位置时指向下面这行的
throw new Exception("exception");
}
}
public class aClass
{
public void ThrowException1()
{
try
{
exceptionClass.throwException();
}
catch(Exception e)
{
throw;
}
}
public void ThrowException2()
{
try
{
exceptionClass.throwException();
}
catch(Exception e)
{
//如果使用这个方法,那么抛出异常的位置是指向这个位置,而不是exceptionClass.throwException();
throw e;
}
}
}
}
也就以下的是更好的方式
try
{
//...some code
}
catch(Exception ex)
{
throw ;
}
待续。。。。。。。。。