Welcome to the Treehouse Community
Looking to learn something new?
Ranvir Sahota9,844 Points
Benefits of throwing an exception
Can someone give me in-depth explaination as well a technical one to explain the benefits of throwing an exception? Thanks
It allows a method to tell whatever called it that it cannot complete whatever task it was given, and also allows it to specify what the error actually was.
Let's take something like
Integer.parseInt(number); that is a function that is meant to take a string and convert it to an int. But what happens when the string it is given does not actually contain a number? The answer is that it has no choice but to thrown an exception. It can't return a number since there isn't one. And while it could return something like
null instead that wouldn't tell the receiving function anything about exactly what type of error actually occurred.
Exceptions not only tell you what type of error has occurred, but they let you set up catch block that allow you to run different code based on what type of error occurred which is definitively useful.
While in an ideal world exceptions wouldn't need to exist it's just a fact of life that errors will occur and as such having a an organized way to handle those errors is important, and that's what exception throwing and catching allows coders to do.