谁能解释一下
catch (Exception ex)
{
throw ex;
}
catch (Exception ex)
{
throw;
}
这个两种代码的区别?
管方的解释是:throw能保留该异常最初引发时所在的堆栈位置。
可是我看好像没有区别..哪位高人能解释一下
catch (Exception ex)
{
throw ex;
}
catch (Exception ex)
{
throw;
}
这个两种代码的区别?
管方的解释是:throw能保留该异常最初引发时所在的堆栈位置。
可是我看好像没有区别..哪位高人能解释一下
{
throw 有错误;
}
catch (Exception 有错误)
{
throw;
}
前者会报出有错误 后者不会
你说的是Fxcop会报错吧...
throw new Exception(ex)就没有堆栈信息了这是没有了.因为都是一个新的Exception了但是 throw ex和throw 我感觉是一样的..
Exception
C# throw与throw ex的区别。
+1如果是我用,那么一定不会用 throw ex ,要么也是 throw new Exception("...", ex); 包装一下一句话:throw ex 修改了错误堆栈的起点,throw 则不会。
以下的代码的确是:throw ex 修改了错误堆栈的起点,throw 则不会。using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;namespace ThrowEx
{
class Program
{ static void Main(string[] args)
{
ThrowSample ts = new ThrowSample();
try
{ ts.ThrowExMethod(); }
catch (Exception ex)
{ Console.WriteLine(ex.ToString()); }
Console.WriteLine("----------------------------------------------------------");
try
{ ts.ThrowExMethod2(); }
catch (Exception ex)
{ Console.WriteLine(ex.ToString()); }
Console.ReadKey();
}
}
class ThrowSample
{
private void ExceptionMethod() { throw new DivideByZeroException(); }
public void ThrowExMethod()
{
try
{ this.ExceptionMethod(); }
catch (Exception ex)
{ throw; }
}
public void ThrowExMethod2()
{
try
{ this.ExceptionMethod(); }
catch (Exception ex)
{ throw ex; }
}
}
}
但是下面的代码就不是这样.复制到VS上执行一下就知道结果不是:throw ex 修改了错误堆栈的起点,throw 则不会。using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;namespace ThrowEx
{
class Program
{ static void Main(string[] args)
{
ThrowSample ts = new ThrowSample();
try
{ ts.ThrowExMethod(); }
catch (Exception ex)
{ Console.WriteLine(ex.ToString()); }
Console.WriteLine("----------------------------------------------------------");
try
{ ts.ThrowExMethod2(); }
catch (Exception ex)
{ Console.WriteLine(ex.ToString()); }
Console.ReadKey();
}
}
class ThrowSample
{
public void ThrowExMethod()
{
try
{ throw new DivideByZeroException(); }
catch (Exception ex)
{ throw; }
}
public void ThrowExMethod2()
{
try
{ throw new DivideByZeroException(); }
catch (Exception ex)
{ throw ex; }
}
}
}
最优的抛出错误是
throw new Exception("", ex);
无论是在本方法还是调用方法出现异常后都会记录原始的错误行号.
throw上抛系统的异常信息,能更清楚的记录异常的调用堆栈,除非你要抛出一个新异常,否则不要用throw exception
把我给出的代码复制到VS执行了,你就在本方法抛出是没区别的...
throw: 只是抛出异常,并没有抛出原异常对象.
对的,throw new Exception("", ex);把错误进行了封装,记录了堆栈错误的行。推荐你使用这种方法。
奇怪了