Python retry equivalent in Java - java

I am very new to java and I am trying out error handling. I am pretty proficent in python and I know the error handling in python would go
while True:
try:
*some code*
except IndexError:
continue
break
I would like to know what the equivalent of a retry loop after exception is in java
EDIT:
This is what I have so far, however whenever a exception is thrown it does an infinite loop saying "Enter an Short: Error Try again."
while(true)
{
try {
System.out.print("Enter an Short: "); //SHORT
short myShort = reader.nextShort();
System.out.println(myShort);
break;
}
catch (InputMismatchException e) {
System.out.println("Error Try again.");
continue;
}
}
To clarify what exactly I would like is. When "InputMismatchException" is thrown the loop re runs and prompts the user again and it does this until the user gives the correct input. I hope that clarifies what I would like it to do.

What you have is almost good as #Thomas mentioned. Just need to add some brackets and semicolons. It should look line following code.
while(true){
try{
// some code
break; // Prevent infinite loop, success should break from the loop
} catch(Exception e) { // This would catch all exception, you can narrow it down ArrayIndexOutOfBoundsException
continue;
}
}

As your question asks about error handling and you showed IndexError as an example, the equivalent in Java could be:
try {
//*some code*
}
catch(ArrayIndexOutOfBoundsException exception) {
//handleYourExceptionHere(exception);
}
About ArrayIndexOutOfBoundsException, you take a look here, in the documentation. About Exceptions, in general, you can read here.
EDIT, according to your question edition, adding more information...
while(true)
{
try {
System.out.print("Enter a short: ");
short myShort = reader.nextShort();
System.out.println(myShort);
}
catch (InputMismatchException e) {
System.out.println("Error! Try again.");
//Handle the exception here...
break;
}
}
In this case, when the InputMismatchException occurs, the error message is exhibited and the break should leave the loop. I do not know yet if I understand well what you are asking, but I hope this helps.

To the help of #Slaw he determined that scanner would keep inputting the same value unless I closed it at the end of the loop and here is the working code.
while (true)
{
Scanner reader = new Scanner(System.in);
try
{
System.out.print("Enter an Short: "); //SHORT
short myShort = reader.nextShort();
System.out.println(myShort);
reader.close();
break;
}
catch (InputMismatchException e)
{
System.out.println("Error Try again.");
}
}

Related

Java try-catch infinite loop when input a character

I want to make a try-catch exception that only accept 1-5 or 9 input. So I wrote the following code.
try {
step1 = scanner.nextInt();
} catch (Exception ex) {
System.out.println("Error! Input accept integers only. Input 1-5 or 9");
System.out.println("");
continue;
}
The result is that if I input an invalid number, it gave me an error (That's true). But when I input a character, it gave me an infinite loop. How can I solve the problem?
Since i don´t know how your loop looks i´ll just go with an endless loop in my answer. In the normal case, the nextInt method wont catch the carriage return, and if you input something that is not a number you need to call nextLine to catch this. If you don´t do this you might run into an infinity loop if you are using any kind of loop that just asks for nextInt. This could solve the problem:
while(true) {
int step1;
try {
step1 = s.nextInt();
} catch (InputMismatchException e) {
System.out.println("Error! Input accept integers only. Input 1-5 or 9");
System.out.println("");
} finally { // Use a finally block to catch the carriage return, no matter if the int that got input was valid or not.
s.nextLine();
}
}
Maybe you must parse input before decision making.
Sorry for my bad English, I'm not a native speaker also.
try this, which make all the tests
int step1;
while (true)
{
Scanner scanner = new Scanner(System.in);
try {
step1 = scanner.nextInt();
if (((step1>=1) && (step1<=5)) || (step1==9))
// BINGO
break;
}
catch (Exception ex)
{
}
System.out.println("Error! Input accept integers only. Input 1-5 or 9");
System.out.println("");
// it loops ther
}
System.out.println("You are done ! "+step1);

Java prints repeatedly if try catch is used

I am making a basic application where it trains your math skills. I have this code:
while (true)
{
try
{
int userAnswer;
System.out.println("Type quit to exit to the menu!");
int randInt = r.nextInt(num2);
System.out.println(num1 + " + " + randInt + " =");
userAnswer = in.nextInt();
if(userAnswer == num1 + randInt) System.out.println("Correct!");
else System.out.println("Wrong!");
break;
}
catch(Exception e)
{
}
}
When someone prints out a d or something in the answer, the try catch goes. But, then it goes to the while loop and repeatedly spams Type quit to exit to the menu and then something like 1 + 2 = infinitely... I think I know what's wrong, userAnswer has been assigned already as something that throws an exception that goes to the catch and it just keeps printing those and goes to the catch and goes back because userAnswer is already assigned. I think this is what is happening, I could be wrong. Please help!
EDIT: I forgot to make this clear, but I want the question to be re-printed again, exiting out of the loop goes to a menu where you can't get the question back, I want it to redo what's in the try catch...
You should never catch an Exception without handling it.
catch(Exception e)
{
System.out.println("An error has occured");
break;
}
This should stop your program from looping infinitely if an Exception occurs.
If user input comes as letter it will get an exception because you are trying to read(parse) as integer. So your catch clause is in the loop you have to write break in there to go out from loop.
Still i will suggest you to getline as string and than compare with your cli commands (quit in your case) than you can try to parse it as an integer and handle loop logic.
You're not breaking the while loop if there is a mismatch
while(true)
{
try
{
}
catch(InputMisMatchException e)//I suggest you to use the exact exception to avoid others being ignored
{
System.out.println("Thank you!");
break;//breaks the while loop
}
}
Yoy're not breaking the loop in case of Exception occurs.
Add break; statement in the catch block to run your program without going to infinite loop, in case exception occurs.
Since the given answers don't match your requirement I'll solve that "riddle" for you.
I guess what you didn't knew is that the scanner won't read the next token if it doesn't match the expectation. So, if you call in.nextInt() and the next token is not a number, then the scanner will throw an InputMismatchException and keeps the reader position where it is. So if you try it again (due to the loop), then it will throw this exception again. To avoid this you have to consume the erroneous token:
catch (Exception e) {
// exception handling
in.next();
}
This will consume the bad token, so in.nextInt() can accept a new token. Also there is no need to add break here.
Mind that in.next() reads only one token, which is delimited by a whitespace. So if the user enters a b c, then your code will throw three exception and therefore generate three different question befor the user can enter a number. You can avoid that by using in.nextLine() instead. But this can lead into another problem: Scanner issue when using nextLine after nextXXX, so pay attention to that :).

multiple statements in try/catch block - Java

Im a bit uncertain as to whether this:
try{
worldHeight = Integer.parseInt(JOptionPane.showInputDialog("How many cells high will the world be?: "));
}
catch (NumberFormatException e){
JOptionPane.showMessageDialog(null, "You have not entered a valid number");
}
try{
worldWidth = Integer.parseInt(JOptionPane.showInputDialog("How many cells wide will the world be?: "));
}
catch (NumberFormatException e){
JOptionPane.showMessageDialog(null, "You have not entered a valid number");
}
would do the same thing as:
try{
worldHeight = Integer.parseInt(JOptionPane.showInputDialog("How many cells high will the world be?: "));
worldWidth = Integer.parseInt(JOptionPane.showInputDialog("How many cells wide will the world be?: "));
}
catch (NumberFormatException e){
JOptionPane.showMessageDialog(null, "You have not entered a valid number");
}
basically want the user to enter a number, if it isnt a number exception gets thrown and the user gets re-asked for a number?
Thanks
In your first example, with the two separate try...catch blocks, it seems that when an exception is thrown, you are just showing a dialog, not stopping the flow of control.
As a result, if there is an exception in the first try...catch, control will continue to the second try...catch and the user will be asked to enter the second number, regardless of the fact that she did not enter the first number correctly.
In the second example, if there is an exception in the first try...catch, the user will not be presented with the second question, because control will not continue inside the try block, but rather after the catch block's end.
Yes this will work (almost) the same. In a try catch block it will only stop execution at the point where the error occurs. If it throws an error at the first line the second line will never be executed in the second option. That is the only difference, in the first option, the second line (input) will be executed no matter if the first line (input) throws an error or not.
You can also try following code
{
int arr[]=new int[5];
try
{
try
{
System.out.println("Divide 1");
int b=23/0;
}
catch(ArithmeticException e)
{
System.out.println(e);
}
try
{
arr[7]=10;
int c=22/0;
System.out.println("Divide 2 : "+c);
}
catch(ArithmeticException e)
{
System.out.println("Err:Divide by 0");
}
catch(ArrayIndexOutOfBoundsException e)
//ignored
{
System.out.println("Err:Array out of bound");
}
}
catch(Exception e)
{
System.out.println("Handled");
}
}
For more detail visit: Multiple try-catch in java with example

How can I end a program during a try catch statement in Java?

I already asked a question about how to have a message pop up and say "please enter a number input" but it was supposed to end the program. Not crash it, but end the program then you would have to rerun it.
` try
{
number = in.nextInt();
if(number >= 8)
{
number = 8;
}
else if (number <= 0)
{
number = 0;
}
}
catch (InputMismatchException exc)
{
System.out.println("Program requires NUMBER input");
}
`
I tried doing a "break;" in the catch (experimented I guess) and it didn't work.
UPDATE: Thanks everyone, I tried return in a previous project and it didn't work. But it worked here so thank you again!!
Use the return statement. That should end the method. System.exit(0) is an alternative option. However, you must be cautious when using System.exit(0) because:
The System.exit method forces termination of all threads in the Java
virtual machine. This is drastic....System.exit should be reserved for
a catastrophic error exit, or for cases when a program is intended for
use as a utility in a command script that may depend on the program's
exit code.
Source: Use System.exit with care
Use System.exit();
try{
...
}
catch (InputMismatchException exc)
{
System.out.println("Program requires NUMBER input");
System.exit(1);
}
Or if your are in the main function, you can just return;
You can just make use simple return; at end of the catch block rather then System.exit(), it will kill the jvm.
Use return;, read also What does the return keyword do in a void method in Java?
public static void main(String[] args) {
return; // END OF PROGRAM :)
}
Returning a Value from a Method
return statement can be used to branch out of a control flow block and exit the method
If you're certain you want the program to terminate you would just do
System.out.println("Program requires NUMBER input");
System.exit(1); // <-- non-zero to indicate an error.
If that's in your main method, do return; otherwise you can do e.g. System.exit(1);

JAVA - Having difficulties with Try / Catch

I'm writing a straight forward Airport Terminal style program for class. I'm going beyond the scope of the assignment and "attempting" to use Try/Catch blocks...
However Java is being that guy right now.
The problem is that when someone enters a non-letter into the following code it doesn't catch then return to the try block it caught...
Why?
Edit - Also the containsOnlyLetters method works, unless someone thinks that could be the error?
System.out.println("\nGood News! That seat is available");
try
{//try
System.out.print("Enter your first name: ");
temp = input.nextLine();
if (containsOnlyLetters(temp))
firstName = temp;
else
throw new Exception("First name must contain"
+ " only letters");
System.out.print("Enter your last name: ");
temp = input.nextLine();
if (containsOnlyLetters(temp))
lastName = temp;
else
throw new Exception("Last name must contain"
+ " only letters");
}//end try
catch(Exception e)
{//catch
System.out.println(e.getMessage());
System.out.println("\nPlease try again... ");
}//end catch
passengers[clients] = new clientInfo
(firstName, lastName, clients, request, i);
bookSeat(i);
done = true;
You seem to misunderstand the purpose and mechanism of try/catch.
It's not intended for general flow control, and more specifically, the meaning is not that the try block is repeated until it finishes without an exception. Instead, the block is run only once, the point is that the catch block will only execute if a matching exception is thrown.
You should use a while loop and if clauses for your code, not try/catch.
If a Throwable or Error is generated it won't be caught by your handler. You could try catching Throwable instead.
What do you mean when you say
when someone enters a non-letter into the following code it doesn't catch then return to the try block it caught...
It is not clear the outcome you expect, are u thinking that once the exception is caught, control will go back into the try block? That is not how it is intended to work.
When an exception is thrown, the control goes to the appropriate catch/finally blocks and then moves ahead, remaining lines in the try block are not executed

Categories