tags:

views:

645

answers:

4

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?

+7  A: 

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

Dani
+4  A: 

I prefer to have as few exits points to 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.

BeWarned
personally i find that better too, but it also depends on the size of the function, sometimes it is cleaner to have multiple exit points (IMHO) than to process a lot of code if an error state has been reached.
Anders K.
+1  A: 

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.

Ashish
If you don't know what exception is thrown, then you have no business catching it. If you catch an exception and don't re-throw, then you had better have resolved the original cause of the exception, which might be out-of-memory, access-violation, buss-error, printer-on-fire, or any number of other things you've never heard of. Only catch what you're expecting. Let everything else go to the caller.
Rob Kennedy
A: 

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

trace