Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

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,520 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.