在catch区块返回?

low*_*ern 58 .net c# exception-handling

在catch块中有一个return语句是错误的吗?有哪些替代方案?
即:

public bool SomeFunction()
{
    try
    {
        //somecode
        return true;
    }
    catch(Exception ex)
    {
        MessageBox.Show(ex.message);
        return false;
    }

}
Run Code Online (Sandbox Code Playgroud)

Svi*_*ack 39

您可以从catch块正常返回.它通常是很好的功能代码.


Mar*_*off 20

一种替代方法是将返回值存储在临时变量中:

public bool SomeFunction()
{
    bool success = true;
    try
    {
        //somecode
    }
    catch(Exception ex)
    {
        MessageBox.Show(ex.message);
        success = false;
    }

    return success;
}
Run Code Online (Sandbox Code Playgroud)

但就个人而言,我发现你编写它的方式(带有一个catch-all catch语句)更具可读性.另一方面,如果您期望一个特定的异常,并且您可能有多个路径可以返回成功...

try
{
    DoTheImportantThing();
    DoTheOtherThingThatMightFailButWeDontCare();
}
catch (DontCareAboutItException ex)
{
    log.Info(ex);
}
catch (Exception ex)
{
    log.Error(ex);
    return false;
}

return true;
Run Code Online (Sandbox Code Playgroud)

然后在我看来,你最好尽可能接近尾声.

作为旁注,根据应用程序,考虑记录您捕获的异常,而不是仅仅向用户显示它们.记录的异常比用户重新计算发生的事情要可靠得多.


Dar*_*rov 11

如果在try块中已经有一个return语句,我可能会把另一个返回放在函数的末尾:

try
{
    //somecode
    return true;
}
catch(Exception ex)
{
    MessageBox.Show(ex.message);
}
return false;
Run Code Online (Sandbox Code Playgroud)

这是为了避免多次返回,如果需要处理多个异常.

  • 如果我遵循将 return 放入 catch 的模式,那么编译器会提醒我错误,如果在重构过程中我不小心删除了 try 中的 return 语句。但是如果我在捕获后继续返回,那么代码将被编译,它可能会以 prod 结束。 (2认同)

And*_*rew 9

没关系,只需要记住,一些代码可以在返回指令后执行(返回值ll被兑现).

    try
    {
        return;
    }
    catch(Exception ex)
    {
        return;
    }
    finally
    {
        //some code
    }
Run Code Online (Sandbox Code Playgroud)


Bar*_*art 8

public bool SomeFunction()
{
    try
    {
        //somecode
        return true;
    }
    catch(Exception ex)
    {
        MessageBox.Show(ex.message);
    }
    return false;
}
Run Code Online (Sandbox Code Playgroud)

我个人将return语句放在方法的底部而不是catch块中.但两者都很好.这完全取决于组织中的可读性(主观)和指导原则.