How can I stop Java catch block executing [duplicate] - java

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

Related

Infinite Loop in My Exception Handling? [duplicate]

This question already has answers here:
How to handle infinite loop caused by invalid input (InputMismatchException) using Scanner
(5 answers)
Closed 5 years ago.
I'm trying to validate a user's input on a menu. Options are 1, 2, 3, and 4. I'm trying to handle the InputMismatchException error when they enter in a letter. I can't see what I'm doing wrong to make my code get stuck in an infinite loop.
System.out.println("What will be your starting balance?");
double startingBalance =0;
boolean check = false;
while(!check) {
try {
startingBalance = input.nextDouble();
check = true;
}
catch (InputMismatchException e) {
System.out.println("Invalid input!");
//startingBalance = 0;
//e.printStackTrace();
//check = false;
}
}
It looks like it get into the catch part, but loops through that repeatedly instead of going back to the try. I tried doing input.nextDouble();
to clear input buffer, but did nothing. Any help would be greatly appreciated.
You can use input.nextLine(); to clear your Scanner in your catch block:
while (!check) {
try {
startingBalance = input.nextDouble();
check = true;
} catch (InputMismatchException e) {
System.out.println("Invalid input!");
input.nextLine();//this will clear your Scanner and repeat again
}
}
Can I ask why you used nextLine() as opposed to nextDouble() ?
because nextLine move the Scanner to the next line
you need to set boolean check = false after first check and also use input.nestLine()

Java Try-catch block, Catch block does not re-prompt the user for a new value [duplicate]

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
}

No exception still not coming out of while loop [duplicate]

This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 9 years ago.
Following is my java code block
i am not able to come out of while block, the same code run's perfect in other module. kindly help me
public void current_ER(View v){
try{
String[] parameters= {uid};
Caller c=new Caller();
c.url="current_ER.php";
c.parameters=parameters;
c.join(); c.start();
String result=MainActivity.result;
System.out.print("before while");
while(result=="START") {
try {
Thread.sleep(10);
System.out.print(result);
}
catch(Exception ex) {
ex.getLocalizedMessage();
System.out.print("in catch");
}
}
System.out.print("after while");
Toast.makeText(this, "ER Details->"+result , Toast.LENGTH_LONG).show();
{
System.out.print("before start indent block");
/////////to next screen////
Intent Manage_Expense=new Intent(this,Manage_Expense.class);
Manage_Expense.putExtra("er_details", result);
//MainActivity.result="START";
Toast.makeText(this, "ER Details->"+result , Toast.LENGTH_LONG).show();
//startActivity(Manage_Expense);
}
}catch(Exception e){
System.out.println(e.getMessage());
}
};
First of all, use:
while("START".equals(result))
In order to compare Strings.
The main error is that you never update result.
At first you set:
String result=MainActivity.result;
So result and MainActivity.result points to the same object.
However, in the other thread you update:
MainActivity.result=resp;
Causing MainActivity.result to point to resp, but result still points to previous value.
If you want to check a variable in a loop, you must make sure the value is changed inside the loop.
When you're going to compare 2 strings it's better to use String.equals(), == operator better works on primitives but not on objects.
As well as using String#equals() make sure the variable is marked as volatile so threads can see changes made by other threads.
i updated my code as follows and it worked
System.out.print("before while");
while("START".equals(MainActivity.result)) {
try {
Thread.sleep(10);
System.out.print(MainActivity.result);
}catch(Exception ex) { ex.getLocalizedMessage();
System.out.print("in catch");
}
}
but i am still unable to figure out why my original code didn't work

Try, catch infinite loop in Java [duplicate]

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.

How to continue execution of a try catch statement in java [duplicate]

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.

Categories

Resources