4 回答
TA貢獻1853條經驗 獲得超18個贊
由于您已經在使用TryParse,因此無需使用try ...catch塊。不僅效率低下,而且也不干凈。只需獲取的返回值DateTime.TryParse并做出決定。
var isDate = DateTime.TryParse(dteCommission.SelectedDate.Value.Date.ToShortDateString(),
接著,if (isDate){...} else {...}
TA貢獻2012條經驗 獲得超12個贊
異常 e 僅用于快速完成它,并且知道真正的異常。給出的錯誤是“可空對象必須有一個值”。System.InvalidOperationException
你怎么知道在運行時它會是一個不同的異常?可以說 NullReferenceException(例如)也許。請記住,所有異常都實現 Exception 對象。
最好像我一樣處理這個問題,還是 If-Else 會更好?
您需要更好地處理錯誤。您知道它可能是 Nullable,因此您需要在繼續之前檢查它是否有價值。您應該注意警告并優雅地處理它們。
如果是這樣,我將如何實施它?
try
{
if(dteCommission.SelectedDate.HasValue)
{
DateTime.TryParse(dteCommission.SelectedDate.Value.Date.ToShortDateString(),
out DueDate);
} else{
MessageBox.Show("Due Date wasn't set. Defaulting to current date.", "Alert",
MessageBoxButton.OK, MessageBoxImage.Warning);
DueDate = DateTime.Parse(DateTime.Now.ToShortDateString());
}
}
catch(Exception e)
{
Log.LogError(e);
MessageBox.Show("Unhandle error occurred please call Admin", "Alert",
MessageBoxButton.OK, MessageBoxImage.Warning);
}
TA貢獻1900條經驗 獲得超5個贊
如果您致力于使用,tryparse那么這是一種更好的方法If-Else,取決于tryparse方法的輸出。但如果您正在使用Parse它,您可能會遇到以下異常之一:
ArgumentNullException(如果參數值為空)
FormatException(如果參數值不是整數值或格式不正確)
FormatException(如果參數值超出整數范圍)
所以最好使用異常處理。
對于第一種方法:
var isParsable = DateTime.TryParse(dteCommission.SelectedDate.Value.Date.ToShortDateString(),
out DueDate);
if (isParsable)
{
//Continue With your Procedure
}
else
{
MessageBox.Show("Due Date wasn't set. Defaulting to current date.", "Alert",
MessageBoxButton.OK, MessageBoxImage.Warning);
}
對于第二種情況,您可以使用:
DateTime DueDate;
try
{
var DueDate = DateTime.TryParse(dteCommission.SelectedDate.Value.ToString());
}
catch (Exception E)
{
MessageBox.Show("Due Date wasn't set. Defaulting to current date.", "Alert",
MessageBoxButton.OK, MessageBoxImage.Warning);
//also you can you the exception type to make it clear for use if it is
// an exception of Null, Format or Argument
}
TA貢獻2039條經驗 獲得超8個贊
我想建議在這種情況下使用 if else 語句而不是異常,它也會被優化,并讓您有機會給出特定于該場景的有意義的消息。
異常處理應該只用于處理未知場景。
- 4 回答
- 0 關注
- 157 瀏覽
添加回答
舉報
