I'm making a program to demonstrate Exception Handling.
(note: the code was written inside towards out)
The user is prompted to input two values (integers) and then the program will divide those values and output the result.
I then added the "try" and "catch keywords for exception handling-instead of the program shutting down if an error occurs,
the words "you cant do that" will appear
I then added a while loop to allow the user another chance to input usable values. Of course, I made sure to make a termination to the loop as well.
Everything works as expected if the user inputs e.g 8 divided by 0. in that case exception occurse, the user is told "you cant do that", is then prompted to start over and so forth until he gives usable integers. then the program continues to the termination
However, if the user inputs a String , e.g 9 divided by xyz, then the program goes into an endless loop
My question is:
1) why does a String cause an endless loop ( I have a theory)
2)why does the loop occur as soon as I put in an incorrect value- is the while loop somehow in extant? somehow always waiting? (hard to picture it)
3) lastly, what would be the correct code to handle and exception caused by a String (as opposed to being caused by impossible to execute math)
Once an Exception is triggered, the remaining code in the try block is never reached. The Exception condition immediately moves the execution to the catch block. Therefore, the x value is never updated to 2 and that results in a loop.
When the loop repeats, the Scanner is still holding on to that invalid content (technically, I believe, the new line character), resulting in the nextInt() call immediately going back into an Exception condition. And now we repeat. Forever.
A quick way to clear the Scanner would be to add to your catch block an statement. That will clear the invalid content held in the Scanner allowing the next iteration of nextInt() to work correctly.
You showed up just in time for the waffles! And this tiny ad:
Building a Better World in your Backyard by Paul Wheaton and Shawn Klassen-Koop