Why do we need exception handling?

exception, syntax

Solution

Suppose you have `func1` calling `func2` with some input.

Now, suppose `func2` fails for some reason.

Your suggestion is to handle the failure within `func2`, and then return to `func1`.

How will `func1` "know" what error (if any) has occurred in `func2` and how to proceed from that point?

The first solution that comes to mind is an error-code that `func2` will return, where typically, a zero value will represent "OK", and each of the other (non-zero) values will represent a specific error that has occurred.

The problem with this mechanism is that it limits your flexibility in adding / handling new error-codes.

With the exception mechanism, you have a generic `Exception` object, which can be extended to any specific type of exception. In a way, it is similar to an error-code, but it can contain more information (for example, an error-message string).

You can still argue of course, "well, what's the `try/catch` for then? why not simply return this object?".

Fortunately, this question has already been answered here in great detail:

In C++ what are the benefits of using exceptions and try / catch instead of just returning an error code?

In general, there are two main advantages for exceptions over error-codes, both of which are different aspects of correct coding:

With an exception, the programmer must either handle it or throw it "upwards", whereas with an error-code, the programmer can mistakenly ignore it.

With the exception mechanism you can write your code much "cleaner" and have everything "automatically handled", wheres with error-codes you are obliged to implement a "tedious" `switch/case`, possibly in every function "up the call-stack".

Problem

I can check for the input and if it's an invalid input from the user, I can use a simple "if condition" which prints "input invalid, please re-enter" (in case there is an invalid input). This approach of "if there is a potential for a failure, verify it using an if condition and then specify the right behavior when failure is encountered..." seems enough for me. If I can basically cover any kind of failure (divide by zero, etc.) with this approach, why do I need this whole exception handling mechanism (exception class and objects, checked and unchecked, etc.)?

Original source

Related problems