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

"throws Exception" - I am not quite getting this. Why should I throw an exception?

In all throughout the EFFICIENCY chapter, I found this and am not sure what it means exactly. Please, anyone, help me out. Thanks in advance.

1 Answer

Your code can throw exceptions when it receives or fails to receive valid data. For example, you can't convert a decimal to an integer without first casting to change its type.

Sometimes it's prudent to check data to make sure it's valid before you try processing it. A common example is to check arguments to make sure they aren't null and to throw an argument exception if a required value isn't present. This keeps you from passing a bug or possibly corrupt data further along in the code. It also aids in unit testing.

A common discussing with exceptions is when to throw them and when to swallow them. swallowing an exception is when your using a try/catch block and receive an exception but decide to let the program continue. This might happen when a user is prompted to select a specific type of file for import but instead selects an different type of file. In this case you might catch the exception when your trying to parse the information and notify the user that the file was invalid or in an unexpected format. You can then return the user back to the program but abort the import process.

What's important is important is to know when to throw an exception and to not let processing continue. For example, if your writing a financial application and your processing small transactions and very large transaction happens it might be best to throw an exception and stop all processing. This forces the user to deal with the invalid amount before it become a larger problem.

I hope this helps.