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