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条经验 获得超7个赞
我想建议在这种情况下使用 if else 语句而不是异常,它也会被优化,并让您有机会给出特定于该场景的有意义的消息。
异常处理应该只用于处理未知场景。
- 4 回答
- 0 关注
- 85 浏览
添加回答
举报