2016-04-06 87 views
1

我有這樣的事情:重新拋出異常是這種情況下

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但未在用戶代碼中處理

如何給我的上述方法的調用者提供自定義錯誤消息?

+0

這就是你在VS輸出窗口中看到的,但**不用擔心**,如果你發現異常,你會得到你提供的消息。順便說一句...我希望真正的程序是不同的(你捕捉到一般的異常,你放棄原來的調用堆棧,你放棄原來的異常,你扔一個無用的通用異常類型...) –

+0

這是一個web服務,winforms,控制檯, wcf還是什麼? – Fabjan

+0

@Fabjan一個類庫,用於不同的平臺 – kkkk00999

回答

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來指示操作是否成功或對byte[](如int.TryParse(或其他TryParse方法))使用out parameter

+0

@Fabjan:添加評論 –

-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 
} 

} 
相關問題