In the try catch block is it bad to return inside the catch? which is good practice

你离开我真会死。 提交于 2019-12-08 14:39:21

问题


In the try catch block is it bad practice to return values from the catch block in C++?

try
{
    //Some code...
    return 1;
}
catch(...)
{
    return 0;
}

Which method of using try/catch is good practice?


回答1:


No, As long as the returned value means what you wanted it to be, you can return anytime. (make sure you've cleared memory if allocated).




回答2:


I prefer to have few exits points in my code, so I would write:

int rc = 1;
try {
  // some code
}
catch(...) {
  rc = 0;
}
return rc;

I find it easier to debug and read code when I only have to keep track of one return statement.




回答3:


i would suggest that if you are not knowing what kind of exception is thrown by code then you can do it.But in this case client has to take action based on return value.

But it would be better if you create user-defined exception and throw it , so that client can come to know what had happened actully . Thats what the actual use of exception and it is recommended for library writer.




回答4:


is a good practice to have it return on the end of the function, after the try/catch block.



来源:https://stackoverflow.com/questions/1713388/in-the-try-catch-block-is-it-bad-to-return-inside-the-catch-which-is-good-pract

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!