Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

try-catch

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?


2 Answers

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).

like image 56
Dani Avatar answered Sep 07 '25 23:09

Dani


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.

like image 43
BeWarned Avatar answered Sep 07 '25 23:09

BeWarned