Exception Handling Advantages

Hi
What is the advantages of using exception handling mechanism instead of plain if statements? Is it possible to resume the program when an exception is thrown or not?
Thanks in advance
closed account (zb0S216C)
Exceptions cannot be ignored, but return-codes can. Events that require immediate attention, such as an allocation failure, are typically thrown, so that the calling function has to respond, no matter what. With return-codes, if an important event arises and a return-code is passed to the calling function, the event can go unnoticed. However, if an exception was thrown, the calling function would have no choice but to either terminate the program, or handle the exception.

Khosravib wrote:
"Is it possible to resume the program when an exception is thrown or not?"

Yes, so long as the exception is caught and handled appropriately.

Exceptions are useful. However, exceptions:

- ...are not suitable for critical points in code
- ...provoke stack winding and stack unwinding
- ...must be handled at all costs
- ...forcefully break the construction of objects (if an exception is thrown during object construction)

Wazzak
Last edited on
What is the advantages of using exception handling mechanism instead of plain if statements?

Exceptions are used when postconditions of a function cannot be satisfied: for example, when a constructor cannot complete its job. They are not used "instead of if statements" because an if statement cannot return from a function: only the return statement and the throw statement do that.

(granted it's possible to catch in the same scope (try if(...) throw ... catch), which would be similar to if(...) ... else, but it's hardly useful)
closed account (3TXyhbRD)
Throw and catch allow multiple datatypes to be returned by a function. You can place all your code in a try block and presume it will work without errors, if any errors happen an exception will be thrown and treated accordingly in catch blocks. Try... catch keep the code more clear and skips extra checks, also solves the error return code. Why would you use try... catch instead of ifs? Try answering the next question: what would your access function return for an empty stack of numbers without double checking if the stack is empty? The access function returns the number on the top of the stack.
Last edited on
Topic archived. No new replies allowed.