在这种情况下,Rethrow是一个例外

时间:2016-04-06 13:45:06

标签: c# exception

我有这样的事情:

public byte[] AnyMethod(){

  try {
    ...
  }
  catch (Exception e) {
    string errorMessage = 
      "Some custom message, which should the caller of that method should receive";

    // I thought something of this ,to pass through my custom exception to the caller?!
    throw new ApplicationException(errorMessage);

    //but this does not allow the method
  }

}

但是这个:

throw new ApplicationException(errorMessage);

将导致:

  

类型' System.ApplicationException'的例外情况发生在... dll但未在用户代码中处理

如何将自定义错误消息提供给我上述方法的调用者?

2 个答案:

答案 0 :(得分:1)

首先,使用自定义例外或至少一个更有意义的例外而不是ApplicationException。其次,如果你的方法抛出它,你必须捕获异常。

因此调用方法还应该将方法调用包装在try...catch

try
{
    byte[] result = AnyMethod();
}catch(MyCustomException ex)
{
    // here you can access all properties of this exception, you could also add new properties
    Console.WriteLine(ex.Message);
}
catch(Exception otherEx)
{
    // all other exceptions, do something useful like logging here
    throw;  // better than throw otherEx since it keeps the original stacktrace 
}

这是一个抽象的简化示例:

public class MyCustomException : Exception
{
    public MyCustomException(string msg) : base(msg)
    {
    }
}

public byte[] AnyMethod()
{
    try
    {
        return GetBytes(); // exception possible
    }
    catch (Exception e)
    {
        string errorMessage = "Some custom message, which should the caller of that method should receive";
        throw new MyCustomException(errorMessage);
    }
}

但请注意,您不应将异常用于正常的程序流程。相反,您可以返回truefalse来指示操作是否成功,或者使用out parameter作为byte[] int.TryParse(或其他TryParse 1}}方法)。

答案 1 :(得分:-1)

publy byte[] AnyMethod(){

try{


}catch(Exception e){

    string errorMessage = string.Format("Some custom message, which should the caller of that method should receive. {0}", e);

    //I thought something of this ,to pass through my custom exception to the caller?!
    throw new ApplicationException(errorMessage);
    //but this does not allow the method
    }

    }

OR

public byte[] AnyMethod(){

try{


}catch(Exception e){

string errorMessage = "Some custom message, which should the caller of that method should receive";

//I thought something of this ,to pass through my custom exception to the caller?!
throw new ApplicationException(errorMessage, e);
//but this does not allow the method
}

}