之前,在使用异常捕获语句try...catch...throw语句时,一直没太留意几种用法的区别,前几天调试程序时发展找不到异常根源,无意中了解到几种使用方法是有区别的。总结如下:
我们都知道,C#中使用throw和throw ex抛出异常,但二者是有区别的。
在C#中推荐使用throw;来抛出异常;throw ex;会将到现在为止的所有信息清空,认为你catch到的异常已经被处理了,只不过处理过程中又抛出新的异常,从而找不到真正的错误源。
throw new Exception()包装一个异常,把内部异常Exception也抛出,这样抛出的异常是最全面详细的异常。
throw的用法主要有以下几种:
第一种(不推荐使用,可惜很多人都一直这么用的),这样适用会吃掉原始异常点,重置堆栈中的异常起始点:
 - try
- {
- }
- catch (Exception ex)
- {
- throw ex;
复制代码 第二种,可追溯到原始异常点,不过编译器会警告,定义的ex未有使用:
 - try
- {
- }
- catch (Exception ex)
- {
- throw;
复制代码 第三种,不带异常参数的,这个同第二种其实一样,可捕获所有类型的异常,IDE不会告警:
 第四种:经过对异常重新包装,但是会保留原始异常点信息。推荐使用。
 - try
- {
- }
- catch (Exception ex)
- {
- throw new Exception("经过进一步包装的异常", ex);
- }
复制代码 下面举例测试:
 - 1 using System;
- 2 using System.Collections.Generic;
- 3 using System.Text;
- 4
- 5 namespace Api.Service.Common
- 6 {
- 7 public class ExceptionClass
- 8 {
- 9 /// <summary>
- 10 /// 抛出异常方法
- 11 /// </summary>
- 12 public void ExceptionThrow1()
- 13 {
- 14 try
- 15 {
- 16 // 调用原始异常抛出方法来抛出异常
- 17 this.ExceptionMethod();
- 18 }
- 19 catch (Exception ex)
- 20 {
- 21 throw ex;
- 22 }
- 23 }
- 24
- 25 /// <summary>
- 26 /// 抛出异常方法1
- 27 /// </summary>
- 28 public void ExceptionThrow2()
- 29 {
- 30 try
- 31 {
- 32 this.ExceptionMethod();
- 33 }
- 34 catch (Exception ex)
- 35 {
- 36 throw;
- 37 }
- 38 }
- 39
- 40 /// <summary>
- 41 /// 抛出异常方法2
- 42 /// </summary>
- 43 public void ExceptionThrow3()
- 44 {
- 45 try
- 46 {
- 47 this.ExceptionMethod();
- 48 }
- 49 catch
- 50 {
- 51 throw;
- 52 }
- 53 }
- 54
- 55 /// <summary>
- 56 /// 抛出异常方法3
- 57 /// </summary>
- 58 public void ExceptionThrow4()
- 59 {
- 60 try
- 61 {
- 62 this.ExceptionMethod();
- 63 }
- 64 catch (Exception ex)
- 65 {
- 66 throw new Exception("经过进一步包装的异常", ex);
- 67 }
- 68 }
- 69
- 70 /// <summary>
- 71 /// 原始异常抛出方法
- 72 /// </summary>
- 73 private void ExceptionMethod()
- 74 {
- 75 throw new DivideByZeroException();
- 76 }
- 77 }
- 78 }
复制代码  - ExceptionClass exceptionClass = new ExceptionClass();
- try
- {
- exceptionClass.ExceptionThrow1();
- }
- catch (Exception ex)
- {
- Console.WriteLine(ex.ToString());
- }
- Console.WriteLine("分割线--------------------------------------");
- try
- {
- exceptionClass.ExceptionThrow2();
- }
- catch (Exception ex)
- {
- Console.WriteLine(ex.ToString());
- }
- Console.WriteLine("分割线--------------------------------------");
- try
- {
- exceptionClass.ExceptionThrow3();
- }
- catch (Exception ex)
- {
- Console.WriteLine(ex.ToString());
- }
- Console.WriteLine("分割线--------------------------------------");
- try
- {
- exceptionClass.ExceptionThrow4();
- }
- catch (Exception ex)
- {
- Console.WriteLine(ex.ToString());
- }
复制代码 举例结果:

我们可以明显看出new Exception()自己包装的异常比较详细,能找到异常的跟踪,其次是throw 都可以找到异常源。
throw ex;会把异常吞掉,抛出新的异常,这样会让开发人员找不到异常源。
推荐使用new Excetion()也就是第四种方式。
免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作! |