【问题标题】:Is it possible to use a method throwing an exception in an if statement condition? c#是否可以使用在 if 语句条件中引发异常的方法? C#
【发布时间】:2020-10-13 20:46:43
【问题描述】:

所以我试图错误处理我的代码,到目前为止,这就是我所拥有的:

date = GetDate(); 
if(date.throws_exception())
{
// would it be possible to make a condition for where you can say if date throws exception?
}

string GetDate()
{
    try
    {
        .
        . 
        .
        return date;
    }
    catch(Exception ex)
    {
        throw new Exception();
    }
}

我想知道 if 条件是否有可能,你能说:

if(date throws exception)

【问题讨论】:

  • 您是否有理由不想在 catch-block 中做这些事情?
  • 是的,以间接方式。不是GetDate 返回一个字符串,而是返回一个元组(bool exceptionThrown, string value),其中的布尔值指示是否抛出了异常。你可以做if(date.exceptionThrown)
  • 有什么原因不能使用内置的DateTime.TryParse 方法吗?
  • 您是否正在尝试制定错误处理策略?如果是这样,您可能希望冒泡您的错误,而不是创建太多 result 对象来检查错误。一个可能有助于您的错误处理策略的链接,如果这是您对这个问题的意图...stackoverflow.com/questions/14973642/…

标签: c# if-statement exception try-catch throw


【解决方案1】:

您可以将方法调用放在 try catch 块中,或重写您的方法以返回结果对象,或指示成功并保存值的元组。

返回元组表示成功的示例:

(bool Success, string Value) GetDate()
{
    try
    {
        .
        .
        .
        return (true, date);
    }
    catch(Exception ex)
    {
        return (false, null);
    }
}

像这样使用:

var result = GetDate(); 
if (result.Success)
{
    // do something with result.Value
}

【讨论】:

  • 类似地,如果您不喜欢元组,请使用“尝试”前缀命名约定,例如 bool TryGetDate(out string Value)。用法:var success = TryGetDate(out string value); if (success) { Console.WriteLine(value); }
  • 根据 Sean 的建议,如果 'Try' 方法已经存在,例如 int.TryParse(),则使用该方法几乎总是比捕获异常并自己处理它们更好。跨度>
  • 就我个人而言,当我结婚时,我将TryGetDate 方法的旧实现归因于[Obsolete]。但我希望其他人的实现不要抛出异常。 ;)
猜你喜欢
  • 2019-07-04
  • 1970-01-01
  • 2018-09-26
  • 1970-01-01
  • 2012-10-10
  • 2020-06-06
  • 2021-05-03
  • 1970-01-01
  • 2022-08-21
相关资源
最近更新 更多