异常使用方法探讨

看了  《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 ;
}

 

 

待续。。。。。。。。。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值