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

How to fix (int) = Integer.parseInt(String) crashing if a word is used instead of a number

I have

(String) = console.readLine("_____"); (int) = Integer.parseInt(String);

If instead of a number I type a word into my console, I get a bunch of errors. How can I instead cause the console to just ask for an actual number instead of crashing?

According to the Java 8 documentation, a NumberFormatException is thrown if the input is not a valid integer. Surround the code involving parseInt with a try-catch block involving NumberFormatException.

1 Answer

According to the Java 8 documentation, a NumberFormatException is thrown if the input is not a valid integer. Surround the code involving parseInt with a try-catch block involving NumberFormatException.