Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Java Java Objects Harnessing the Power of Objects Handling Exceptions

Ranvir Sahota
Ranvir Sahota
9,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

1 Answer

andren
andren
28,558 Points

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.

Ranvir Sahota
Ranvir Sahota
9,844 Points

Thanks for that that helped clear a few things up. I just ask these types of questions for the design of my code.