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.
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
This question already has answers here:
try/catch with InputMismatchException creates infinite loop [duplicate]
(7 answers)
Closed 6 years ago.
I am new to Java and would like to ask you a question.
I have written the below code where "numOfThreads" should be assigned a valid int value by the user through the Console.
However, I would like to achieve a result where if the input is incorrect and we go in the catch block, the user should be re-prompted to enter "numOfThreads" until it is of correct type and range.
For some reason I seem to go into infinite loop. Can you please assist? Thanks :)
import java.util.Scanner;
public class Main {
public static void main(String args[]){
int numOfThreads;
boolean promptUser = true;
Scanner keyboard = new Scanner(System.in);
while (promptUser)
{
try{
numOfThreads = keyboard.nextInt();
promptUser = false;
}
catch(Exception e){
System.out.println("Entry is not correct and the following exception is returned: " + e);
numOfThreads = keyboard.nextInt(); // DOES NOT SEEM TO BE ASKING FOR A NEW INPUT
}
}
}
}
it doesn´t because nextInt tries to consume the last token. When there is an invalid input it can´t consume it. As a result a following nextInt call wont be able to consume it either. write a keyboard.nextLine before numOfThreads = keyboard.nextInt(); and you are fine.
catch(Exception e){
System.out.println("Entry is not correct and the following exception is returned: " + e);
// this consumes the invalid token now
keyboard.nextLine();
numOfThreads = keyboard.nextInt(); // It wasn´t able to get the next input as the previous was still invalid
// I´d still rewrite it a little bit, as this keyboard.nextInt is now vulnerable to throw a direct exception to the main
}
This question already has answers here:
What is a NumberFormatException and how can I fix it?
(9 answers)
Closed 6 years ago.
Is there a way to handle the number(order) of NumberFormatException? I made a calculator using Double operand[], and like below, I want to write when did error occurred. When I put the input "2+k", the message saying that "operand[1] has the wrong input." should come out. How should I do like that?
First, replace the line
System.out.println("operand[] has the wrong input.");
with the line
System.out.println(e.getMessage());
Now you can pass a message when you throw the exception in the MyCalculator.calculate() method using the NumberFormatException(String) constructor. It would look something like this:
calculate(String expression)
{
//validate input code
//...
//if operand 0 not valid
throw new NumberFormatException("operand 0 has the wrong input");
//if operand 1 not valid
throw new NumberFormatException("operand 1 has the wrong input");
//rest of calculate method
}
Maybe you could define a new exception. As for example CalculatorException which could contain more specific information about calculations, as for example which operand is incorrect. Or you could even define one more exception like IllegalOperandException which could extend CalculatorException. And then your method calculate could be declared to throw a CalculatorException. In conclusion, the idea is to define a new hierarchy of exceptions to give information more related to the domain of your problem.
And then, your code could be so:
try {
System.out.println("result: " + MyCalculator.calculate(expression));
System.out.println();
} catch(CalculatorException e) {
System.out.println(e.getMessage());
}
This question already has answers here:
How to handle infinite loop caused by invalid input (InputMismatchException) using Scanner
(5 answers)
Closed 7 years ago.
I'm trying to make sure that the users input is an integer but when I use the below code I just get an infinite loop of the print statement. Any advice of how to improve?
boolean valid = false;
System.out.println("What block are you gathering? (use minecraft block ids)");
while(valid == false){
try{
block = input.nextInt();
valid = true;
}
catch(InputMismatchException exception){
System.out.println("What block are you gathering? (use minecraft block ids)");
valid = false;
}
}
nextInt() doesn't consume invalid input so it will try read same invalid value over and over again. To solve this problem you need to consume it explicitly by calling next() or nextLine() which accept any value.
BTW to make your code cleaner and avoid expensive operations like creating exceptions you should use methods like hasNextInt() .
Here is how you can organize your code
System.out.println("What block are you gathering? (use minecraft block ids)");
while(!input.hasNextInt()){
input.nextLine();// consume invalid values until end of line,
// use next() if you want to consume them one by one.
System.out.println("That is not integer. Please try again");
}
//here we are sure that next element will be int, so lets read it
block = input.nextInt();
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.