Why Do We Need Exceptions in Code?
Join the DZone community and get the full member experience.Join For Free
Assume you have the following
Bank class. In this code, the
withdraw method is our main focus. Its job is to deduct a given amount from the balance and then return the updated balance.
As you notice, it can return only a
double. I would say that this function can only speak in "double" language, poor function.
Currently, withdraw function can speak only one language,
the"return type" language
There is a banking rule waiting to be implemented, which is "an account overdraft should not be allowed". For this rule, there is one solution we can silently return the current balance without deducing the amount.
But, this solution does not inform the client (in this case the main method) about the reason why the balance is not changed; actually, it says nothing to the client. The client has to figure out whether the request granted or not.
If the client notices the balance did not change, it can only guess!
Possible reasons could be:
- There is a daily limit?
- The balance is not adequate?
- There is a minimum balance rule?
But poor function cannot express itself. It cannot speak any other language: It can only speak (return) in "double" language.
With the exception mechanism,
a function can speak many other languages.
Look at the code below. Now, our withdraw function can speak "string" language as well. Now, it can express more than before, yay!!
If there is a daily limit, we can now implement it, and we can inform the client if it's violated. Let's look at the code below.
Exception keeps your client in the know
Your client has a right to know why something has not happened, or where did the client make a mistake. Exception enables your client in the know.
Exception enables your function to express more than the "return type" value.
Exception enables your function to speak in any languageD
Published at DZone with permission of Murat Gungor. See the original article here.
Opinions expressed by DZone contributors are their own.