我可以對我設定的條件而不是實際錯誤使用 try-catch-throw 嗎?例如,
int x = 0;
if (x > 0)
{ throw new Exception("X can't be more than 0!");}
所以x 大于 0 在技術上沒有任何問題,但這是我的條件。另外,我知道 throw 會終止程式,但我需要程式在之后繼續運行。
編輯:這是我試圖在其上實作的代碼的一部分:
public bool CheckIfEligible()
{
if (DateTime.Compare(DateTime.Now, this.startTime) > 0)
{
Console.WriteLine("\n" "ERROR: choose a later date");
return false;
}
// bunch of other conditions here...
else
return true;
}
uj5u.com熱心網友回復:
實際上,創建代表您的域的特殊情況的自定義例外通常是一種很好的做法。
public class StartCannotBeInThePastException : Exception
{
public StartCannotBeInThePastException(string message) : base(message)
{ }
}
這種方式可以專門處理那些代表特定域相關錯誤的例外,然后記錄詳細資訊或回傳給客戶端,而不是使應用程式崩潰。執行自定義例外的另一個好處是您可以在代碼中明確您的業務規則,使其更易于閱讀。
在這個例子中將是這樣的:
public void CheckIfEligible()
{
if (DateTime.Now > this.startTime)
{
throw new StartCannotBeInThePastException();
}
}
例外有一些隱藏的性能成本,如果您對此感興趣,我給您留了這個視頻,它很好地解釋了它。
https://youtu.be/2f2elFRmeLE
uj5u.com熱心網友回復:
這假設您沒有將此代碼作為某個庫提供,但主要關注在開發它時進行這些型別的檢查。
C# 具有[ConditionalAttribute("DEBUG")]可以將其添加到將執行這些檢查的方法的屬性,僅當代碼處于DEBUG模式而不是釋放時。
為什么?
它允許在我們發布之前進行健全性檢查。
這意味著,只有在除錯模式構建時才應編譯呼叫和使用的方法。當代碼在模式中構建時,它永遠不會被呼叫或編譯到 exe 中;因此不要在發布代碼中進行開發檢查,這很可能不會看到開發型別失敗。Release
例如
[ConditionalAttribute("DEBUG")]
private void CheckIfEligible(DateTime start, Datetime end)
{
if (DateTime.Compare(DateTime.Now, startTime) > 0)
Console.WriteLine($"{Environment.Newline}ERROR: choose a later date");
if (start > end)
Console.WriteLine($"{Environment.Newline}ERROR: choose a earlier date");
}
然后在你的代碼中做這樣的事情。
public void MyOperation()
{
....
CheckIfEligible(myStartTime, myEndTime);
// Normal processing no extra checks needed
If () ...
}
這使您可以在不影響最終結果的情況下執行此程序似乎建議您想要的健全性檢查。
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/362411.html
下一篇:從方法中捕獲例外
