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.
   at WindowsApplication2.Class1.DoSomething() in l:\vs.net-projektit\windowsapplication2\main.cs:line 15
   at WindowsApplication2.Form1.button1_Click(Object sender, EventArgs e) in l:\vs.net-projektit\windowsapplication2\form1.cs:line 103

 

 

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 ;
			}
		}
	}


And of course for all rethrow statements, the stack trace is now like:

System.DivideByZeroException: Attempted to divide by zero.
   at WindowsApplication2.Class3.DoSomething() in l:\vs.net-projektit\windowsapplication2\main.cs:line 46
   at WindowsApplication2.Class2.DoSomething() in l:\vs.net-projektit\windowsapplication2\main.cs:line 30
   at WindowsApplication2.Class1.DoSomething() in l:\vs.net-projektit\windowsapplication2\main.cs:line 15
   at WindowsApplication2.Form1.button1_Click(Object sender, EventArgs e) in l:\vs.net-projektit\windowsapplication2\form1.cs:line 103

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".

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值