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

In Java Data Structures, why does Craig need to put "throws clause" on his method promptNewSong()? What does it do?

I noticed that Craig needed to throw a new IOException on the method header for promptAction() and on promptNewSong(). Both of these methods are located in KaraokeMachine class. He also puts a try/catch block in the method run(). Do these IOExceptions automatically know to look inside the try/catch block in the method run() or what purpose are they serving in this example in particular? The video that I am describing in particular is Menu UI video inside Java Data Structures course.

1 Answer

The throws keyword tells Java that the method does something that can cause a certain exception and that the method itself has no try/catch clause to deal with that potential exception, which means that the exception has to be handled by whatever ends up calling said method instead.

Since those methods are called within the run method that is where the potential exceptions will end up being thrown to if they actually occur, and therefore that's where a try/catch clause is needed.

So simply summarized throws is just a way of telling Java "Yes, I know there is a potentially unhandled exception in this method, but I don't want to deal with it right here so make the code that calls the method deal with it instead".

Thank you for clarifying! andren