This question already has answers here:
try/catch with InputMismatchException creates infinite loop [duplicate]
(7 answers)
Closed 7 years ago.
I really have no idea about this problem...
The block catches an exception if the number is not correct, when I put -1 or 0 it catches the Exception and asks me to input the number again... but if I type something like asdasd it will run an infinite loop.
while (true){
try{
System.out.println("-Size of the array: ");
size = read.nextInt();
if(size<=0){
throw new Exception();
}else{
break;
}
}
catch(Exception e){
System.out.println("\n-Wrong input. Try again.\n");
}
}
Probably the best way to deal with this is to change it so that reader gets the next line:
String input = read.nextLine();
if(input.length() == 0) { continue; }
try{
size = Integer.parseInt(input);
} catch(NumberFormatException e){ throw new Exception(); }
Put the Scanner initialization inside while loop:
while (true){
try{
Scanner read = new Scanner(System.in);
System.out.println("-Size of the array: ");
size = read.nextInt();
if(size<=0){
throw new Exception();
}else{
break;
}
}
catch(Exception e){
System.out.println("\n-Wrong input. Try again.\n");
}
}
My guess is that read.nextInt is throwing an exception because "asdasd" is not an integer. This will cause your exception handler to be run and print the message. However, because you don't have "break" in your exception handler, the loop will be run again... and again...
I suspect that you are getting caught out because you are throwing and catching Exception. If you add e.printStackTrace(); to the catch plock that you will probably find that you are catching an exception that you are not expecting to happen ... like one coming from the nextInt() call, or an NPE or something.
Don't throw Exception. Not ever. Use a specific exception, creating one for your self if none of the standard ones is appropriate.
Don't catch Exception unless you are prepared to deal with ALL of the possibilities. And that includes all of those unexpected unchecked exceptions that are due to random bugs in your code.
Related
This question already has answers here:
How to handle infinite loop caused by invalid input (InputMismatchException) using Scanner
(5 answers)
try/catch with InputMismatchException creates infinite loop [duplicate]
(7 answers)
Catching an InputMismatchException until it is correct [duplicate]
(4 answers)
Closed 3 years ago.
Here's a part of me code. Well, my question is how can I skip catch block when I enter wrong values? For example, as you can see I need coordinates to be double or Float but when I enter String it starts infinite while looping. How can I prevent it and make program start from the begining until user enters right values?
main_loop:
while (true) {
int i = 3;
System.out.println("Attemts left: " + i);
loop_label:
while (true) {
try {
temp_coords.setX(temp_scn.nextDouble());
temp_coords.setY(temp_scn.nextFloat());
break main_loop;
} catch (Exception e) {
System.out.println("wrong format!");
} finally {
break loop_label;
}
}
i--;
if(i == 0){
break;
}
}
This is my code without loops and labels
How can I can make this code work until right data coming in
try {
temp_coords.setX(temp_scn.nextDouble());
temp_coords.setY(temp_scn.nextFloat());
} catch (Exception e) {
System.out.println("wrong format!");
}
break loop_label
Should be in the catch block. Do not use finally because the code inside it will be run even if no error is thrown.
And as Andy said, it seems i will never be equal to 0
OK, here's my problem. Our teacher wants us to create a program that creates a Fibonacci sequence and then the user can do operation with the array of numbers (like get number at an index, etc). I wanted to go above and beyond and idiot-proof it. I asked her about try/catch statements but she said that it was not in the curriculum.So, I did research and made this code:
while( valid ) {
try {
lengthOfSequence = keyboard.nextInt();
} catch ( Exception e ) {
out.println( "You entered an " + e + ". Please enter a number between 1 and " + maxLength );
throw e;
}
}
(valid it true initially) So the code is supposed to get an integer that the user inputs. Then take that integer and assign it to lengthOfSequence. Running it properly (inputting an integer) will allow the code to run correctly, but when I plug in a "o" (or any other string) for my input, the catch is not catching the Exception and I get this error:
java.util.InputMismatchException
at java.util.Scanner.throwFor(Scanner.java:909)
at java.util.Scanner.next(Scanner.java:1530)
at java.util.Scanner.nextInt(Scanner.java:2160)
at java.util.Scanner.nextInt(Scanner.java:2119)
at FibonacciRunner.main(FibonacciRunner.java:28)
I've tried many ways to try to fix it including:lengthOfSequence = Integer.parseInt( keyboard.nextLine() ); which gives me
java.lang.NumberFormatException: For input string: "o"
at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
at java.lang.Integer.parseInt(Integer.java:492)
at java.lang.Integer.parseInt(Integer.java:527)
at FibonacciRunner.main(FibonacciRunner.java:29)
I've also tried naming the exception InputMismatchExceptionand NumberFormatException but still I get an error.
I'm a novice at coding and at Stack Overflow, so thank you in advance for the help
EDIT:
I have tried removing the throw e but all that does is create an endless loop of the code outputting "You entered an java.util.InputMismatchException. Please enter a number between 1 and 101".
Also I removed this from the try statement because I thought it would not pertain to the question
if( lengthOfSequence > 1 && lengthOfSequence < maxLength ) {
fibonacci.createSequence( lengthOfSequence );
valid = false;
}
Change your code to:
boolean valid = false;
while( !valid ) {
try {
lengthOfSequence = keyboard.nextInt();
valid = true;
} catch ( Exception e ) {
out.println( "You entered a wrong value. Please enter a number between 1 and " + maxLength);
}
}
If you throw the exception, as you did in:
throw e;
Your program will no longer catch it and will suspend execution.
Remove throw e;, that's all you need to do. You have already caught the exception in the catch clause, if you throw it then your calling method would have to catch it again. But since the calling method does not have a try-catch mechanism, program will terminate and give you UNCAUGHT EXCEPTION
Titus answered my question as a comment but because I cant mark a comment as a question Ill just answer it myself:
This question is similar to: How to handle infinite loop caused by invalid input using Scanner
Quoting Titus:
to stop the loop when you receive bad input, you will have to consume that input in the catch block, you can do that by adding this statement in the catch block: keyboard.next() or keyboard.nextLine()
So I just added a keyboard.next(); to my catch block and removed the throw e and it stopped bugging out. Thank you guys!
This question already has answers here:
How to handle infinite loop caused by invalid input (InputMismatchException) using Scanner
(5 answers)
Closed 5 years ago.
Help, I am completely new to java and I am trying to create a loop that will ask for an input from the user which is to be a number. If the user enters anything other than a number I want to catch the exception and try again to get the correct input. I did this with a while loop however it does not give the opportunity after the error for the user to type in anything it loops everything else but that. Please help me to see understand what is wrong and the correct way to do this... Thank you. This is what I have:
import java.util.Scanner;
import java.util.InputMismatchException;
public class simpleExpressions {
public static void main (String[] args) {
Scanner keyboard = new Scanner(System.in);
while ( true ) {
double numOne;
System.out.println("Enter an Expression ");
try {
numOne = keyboard.nextInt();
break;
} catch (Exception E) {
System.out.println("Please input a number only!");
} //end catch
} //end while
} //end main
while ( true )
{
double numOne;
System.out.println("Enter an Expression ");
try {
numOne = keyboard.nextInt();
break;
}
catch (Exception E) {
System.out.println("Please input a number only!");
}
This suffers from several problems:
numOne hasn't been initialized in advance, so it will not be definitely assigned after the try-catch, so you won't be able to refer to it;
if you plan to use numOne after the loop, then you must declare it outside the loop's scope;
(your immediate problem) after an exception you don't call scanner.next() therefore you never consume the invalid token which didn't parse into an int. This makes your code enter an infinite loop upon first encountering invalid input.
Use keyboard.next(); or keyboard.nextLine() in the catch clause to consume invalid token that was left from nextInt.
When InputMismatchException is thrown Scanner is not moving to next token. Instead it gives us opportunity to handle that token using different, more appropriate method like: nextLong(), nextDouble(), nextBoolean().
But if you want to move to other token you need to let scanner read it without problems. To do so use method which can accept any data, like next() or nextLine(). Without it invalid token will not be consumed and in another iteration nextInt() will again try to handle same data throwing again InputMismatchException, causing the infinite loop.
See #MarkoTopolnik answer for details about other problems in your code.
You probably want to use a do...while loop in this case, because you always want to execute the code in the loop at least once.
int numOne;
boolean inputInvalid = true;
do {
System.out.println("Enter an expression.");
try {
numOne = keyboard.nextInt();
inputInvalid = false;
} catch (InputMismatchException ime) {
System.out.println("Please input a number only!");
keyboard.next(); // consume invalid token
}
} while(inputInvalid);
System.out.println("Number entered is " + numOne);
If an exception is thrown then the value of inputInvalid remains true and the loop keeps going around. If an exception is not thrown then inputInvalid becomes false and execution is allowed to leave the loop.
(Added a call to the Scanner next() method to consume the invalid token, based on the advice provided by other answers here.)
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Java: Try-Catch-Continue?
I'm reading in information from a text file and I want my code to throw an exception if there is an invalid type being read. However, I can't figure out how to have my program continue after an exception has been found
while(input.hasNext()) {
try{
type = input.next();
name = input.next();
year = input.nextInt();
} catch(InputMismatchException ex)
{
//System.out.println("** Error: Invalid input **");
//code to make program continue
}
}
You can either just let the thread leave the catch block - code execution will continue after that. If you want to skip the code after the catch block, you can use the continue keyword within a while loop...
If you want to retrieve a year after retrieving the name failed with an exception, then you will have to put a try ... catch around each input.next...() statement. You cannot restart execution at the point the exception has been thrown.
I have a java program that is supposed to handle an Exception, but the end result is far from what I intended it to be. Here is the overall idea of my program: it is supposed accept an input of zero and exit the program. The input dialog should cause an Exception which should be caught and print the message "bad number".
My brain is telling me I'm missing one line of code in the catch block.
here is my code:
import javax.swing.JOptionPane;
public class exceptTest {
public static void main(String[] args){
try {
String line = JOptionPane.showInputDialog(null, "enter number");
if(line.equals ("0"));
System.exit(0);
}catch(Exception e){
JOptionPane.showMessageDialog(null, "bad number");
}
}
}
You are not catching an exception here, you are simply making a if statement, you can just use an if/else.
try{
String line = JOptionPane.showInputDialog(null, "enter number");
if(line.equals ("0")){
System.exit(0);
}else{
JOptionPane.showMessageDialog(null, "bad number");
}
}catch (Exception ex){
ex.printStackTrace();
}
The catch you would only use for any exceptions showInputDialog() throws, but for your number check you are not catching anything, it just simply is not 0.
You don't execute your exception handling code because you never throw an exception. The code will execute the input, then test the input to be equal to "0", then based on that will or will not display a dialog, and then it will execute.
The throwing of an exception occurs either because something has happened outside the conditions that the code will handle, or because you throw one explicitly.
By "outside the conditions" etc., I mean something like dividing by 0. Java (nor any other language) will handle that, and an exception will be thrown. The normal steps of procedural processing will stop, and an execution handler will be called.
In your case, if you (for instance) attempted to parse the input to be a number, but the input was not a number, you would get an exception. This is different functionality than you say you wanted, but is a better illustration of what an exception is for. Something like
try
{
int numberEntered = Integer.parse(line);
JOptionPane.showMessageDialog(null, "Entered a number, parsed to " + numberEntered);
}
catch (NumberFormatException nfe)
{
JOptionPane.showMessageDialog(null, "Did not enter a number, but <" + line + ">");
}
shows the sort of thing exceptions are normally good for.
If you wanted to, you could define an exception, call it BadNumberException, and throw it in the code you have -- you would put it (I guess) in an else clause for your if statement. But your routine would be throwing the exception, and I think it is unusual for the routine that throws an exception to also catch it.
Hope that helps.
rc
You have a semi-colon after your if statement, it terminates the line and the compiler does not look for the rest of the if. Remove your semi-colon and it will work fine.
import javax.swing.JOptionPane;
public class exceptTest
{
public static void main(String[] args){
try
{
String line = JOptionPane.showInputDialog(null, "enter number");
if(line.equals ("0")) //semi-colon removed here
{
System.exit(0);
}
throw new IllegalArgumentException("Input was not 0");
}
catch(Exception e)
{
JOptionPane.showMessageDialog(null, "bad number");
}
}
}
Your code does not throw an exception if the input is not equal to 0. Therefore, you never catch anything, thus no errormessage is shown on the screen.
You could do two things:
- throw an exception if the input is not 0 (then you will enter the catch)
or
- use an else with your if that displays the error message (then you don't need the try-catch for checking whether the input is 0)
Edit: And of course as Hunter McMillen noticed, you need to remove the semicolon after your if statement.