在try catch块中,在catch中返回是不是很糟糕?这是一个很好的做法

19 c++ try-catch

在try catch块中,从C++中的catch块返回值是不好的做法吗?

try
{
    //Some code...
    return 1;
}
catch(...)
{
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

使用try/catch的哪种方法是好的做法?

Dan*_*ani 29

不,只要返回的值表示您想要的值,您就可以随时返回.(如果已分配,请确保已清除内存).


BeW*_*ned 6

我更喜欢在我的代码中有几个退出点,所以我会写:

int rc = 1;
try {
  // some code
}
catch(...) {
  rc = 0;
}
return rc;
Run Code Online (Sandbox Code Playgroud)

当我只需要跟踪一个return语句时,我发现调试和读取代码更容易.

  • 我个人觉得它也更好,但它也取决于函数的大小,有时候,如果达到错误状态,有多个退出点(恕我直言)比处理大量代码更清晰. (7认同)