将异常传递给方法

时间:2016-11-07 11:06:31

标签: c# exception

private static void Foo(Exception e)
{
  e = new Exception("msg1");
}

static void Main(string[] args)
{
  try
  {
    int zero = 0;
    int ecks = 1 / zero;
  }
  catch (Exception e)
  {
    // I thought Exception is passed by reference, therefore Foo changes e to 
    // point to new Exception instance with message "msg1".
    // But it stays the same
    Foo(e);
    throw e;
  }
}

适用于类别。

public class MyClass
{
  public string Name { get; set; }
}

private static void Foo(MyClass m) { m.Name = "bar"; }

static void Main(string[] args)
{
  Voda v = new Voda();
  v.Name = "name";
  Foo(v); // v.Name gets value "bar"
}

根据msdn例外是阶级。

修改

private static void Foo(Exception e)
{
  while (e != null && e.InnerException != null)
  {
    // I'm changing where e points.
    // Therefore caller Exception should now point to most inner exception
    e = e.InnerException;
  });
}

3 个答案:

答案 0 :(得分:1)

当您致电方法Foo(e)时,e内的参考副本会传递给Exception e,以便原始eException e指向同一位置。然后你更改Exception e内的引用,它指向其他一些异常。但原始e中的引用仍然保持不变,因为它是“按值传递”而不是“按引用传递”的情况。

答案 1 :(得分:0)

尝试参考

private static void Foo(ref Exception e)
{
  e = new Exception("msg1");
}

static void Main(string[] args)
{
  try
  {
    int zero = 0;
    int ecks = 1 / zero;
  }
  catch (Exception e)
  {
    // I thought Exception is passed by reference, therefore Foo changes e to 
    // point to new Exception instance with message "msg1".
    // But it stays the same
    Foo(ref e);
    throw e;
  }
}

答案 2 :(得分:0)

以下行只是在当前的Foo方法堆栈中创建了一个有效的新对象。原始main方法仍然指向原始异常对象。

e = new Exception("msg1");

要为MyClass类重现此操作,那么MyClass将会出现相同的情况:

private static void Foo(MyClass m) { m = New MyClass();  m.Name = "bar"; }