繁体   English   中英

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

[英]Rethrow an exception is this case

我有这样的事情:

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

将导致:

在... dll中发生了'System.ApplicationException'类型的异常,但未在用户代码中处理

怎么做自定义errror消息给我上面提到的方法的调用者?

首先,使用自定义异常或至少一个更有意义的异常而不是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 byte[]out参数 ,如int.TryParse (或其他TryParse方法)。

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
    }

    }

要么

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
}

}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM