[英]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);
}
}
但請注意,不應將異常用於正常的程序流程。 相反,您可以返回true
或false
以指示操作是否成功,或者使用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.