Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why use exception instead of returning error code [duplicate]

Tags:

c++

exception

Possible Duplicate:
Exceptions or error codes

Hi,

I am looking for some guidelines on when to use return values v/s exceptions.

Many thanks in advance.

like image 460
LionHeart Avatar asked Oct 03 '10 15:10

LionHeart


People also ask

Why is using exceptions a better idea than returning an error value?

When you code using return codes, you're preparing yourself for failure, and hope your fortress of tests is secure enough. When you code using exception, you know that your code can fail, and usually put counterfire catch at chosen strategic position in your code.

Why use exceptions instead of error codes?

Use exceptions to check error conditions that might occur at run time even if your code is correct, for example, "file not found" or "out of memory." Exceptions can handle these conditions, even if the recovery just outputs a message to a log and ends the program.

Why using exceptions?

Exceptions provide the means to separate the details of what to do when something out of the ordinary happens from the main logic of a program. In traditional programming, error detection, reporting, and handling often lead to confusing spaghetti code.

What is meant by error code and exception?

Error codes mean that you must carefully look at function calls to see if the programmer handled the possible errors. Exceptions mean that you must imagine what happens if an exception is thrown anywhere in the flow.


1 Answers

Errors are often detected at a very low level in your code, but handled at a very high level. If you use return codes for these, you have to design all the intermediate levels to expect the low level code and propagate it up until something handles it. With exceptions, you only need to throw at the low level, and catch at the high level (if at all). As long as your intermediate level code uses RAII, you don't have to change any of that to do the error propagation.

So I often think about the type of error and where it's likely to be handled. If the caller is likely to handle the problem, because it's expected to be a common thing, then a return code is great. If the error is something catastrophic (cannot allocate a necessary resource), then the immediate caller cannot be expected to handle it.

Other things to consider: Exceptions cannot be ignored, return codes can. Use an exception when it would be dangerous for the problem to go unhandled.

Technically, exceptions cannot propagate back up through C code. (It works on many systems, but it's not portable nor guaranteed.) So if you've got a C library calling back into your C++ code, you probably shouldn't throw an exception from the callback. Likewise for thread boundaries, etc.

like image 76
Adrian McCarthy Avatar answered Oct 07 '22 14:10

Adrian McCarthy