Program throwing exception despite generic Exception e catch [closed] - java

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 1 year ago.
Improve this question
public class TryCatch {
public static void main(String[] args) {
int Score[] = {5,3,9}; //my array
Scanner sc = new Scanner(System.in);
boolean flag=true; //boolean for the while loop that will keep on asking for input till the input is correct
System.out.println("Enter index: ");
int ind = sc.nextInt(); //taking input
while(flag){
try {
System.out.println("Value at index is = " + Score[ind]);
flag= false; //if input is correct, the bool turns false and loop stops
} catch (Exception e) {
System.out.println("Enter a valid value!");
ind = sc.nextInt(); //should ask for input again if the input isn't right
}
}
}
}
So the problem I am having is that the catch block works for ArrayOutOfBound exception, but not when I enter some other character like a letter. What should I do?
UPDATE:
I fixed the bug by creating a new instance of the scanner class object in the catch block.
sc = new Scanner(System.in);
Thank you all for your answers.

You need to initialize the scanner class object again to close the previous scanner and dump all the input in it.
Add this line to the end of your catch block-
sc = new Scanner(System.in);

It is happening because you are asking for integer input within the catch, which isn't handled anywhere else, try this:
int ind; //taking input
while(flag){
try {
find = sc.nextInt();
System.out.println("Value at index is = " + Score[ind]);
flag= false; //if input is correct, the bool turns false and loop stops
} catch (Exception e) {
System.out.println("Enter a valid value!");
continue;
}
}

The problem is that the exception is thrown outside of the try block. You read from the keyboard either before the try-catch block or in the catch block.

If an exception is thrown within a catch block that exception will not be caught. Also you need to clear the input with nextLine or you will get an infinite loop, the correct code would be as follows:
System.out.println("Enter index: ");
while (flag) {
try {
int ind = sc.nextInt(); //taking input
System.out.println("Value at index is = " + Score[ind]);
flag = false; //if input is correct, the bool turns false and loop stops
} catch (Exception e) {
System.out.println("Enter a valid value!");
sc.nextLine();
continue;
}
}

I believe you need to separate the exceptions (when catching multiple types) with a pipe operator (SQLException | IOException e)
for example.

Related

Program loops when invalid character is entered [duplicate]

This question already has answers here:
How to handle infinite loop caused by invalid input (InputMismatchException) using Scanner
(5 answers)
Closed last month.
So I'm building a program which takes ints from user input. I have what seems to be a very straightforward try/catch block which, if the user doesn't enter an int, should repeat the block until they do. Here's the relevant part of the code:
import java.util.InputMismatchException;
import java.util.Scanner;
public class Except {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
boolean bError = true;
int n1 = 0, n2 = 0, nQuotient = 0;
do {
try {
System.out.println("Enter first num: ");
n1 = input.nextInt();
System.out.println("Enter second num: ");
n2 = input.nextInt();
nQuotient = n1/n2;
bError = false;
}
catch (Exception e) {
System.out.println("Error!");
}
} while (bError);
System.out.printf("%d/%d = %d",n1,n2, nQuotient);
}
}
If I enter a 0 for the second integer, then the try/catch does exactly what it's supposed to and makes me put it in again. But, if I have an InputMismatchException like by entering 5.5 for one of the numbers, it just shows my error message in an infinite loop. Why is this happening, and what can I do about it? (By the way, I have tried explicitly typing InputMismatchException as the argument to catch, but it didn't fix the problem.
You need to call next(); when you get the error. Also it is advisable to use hasNextInt()
catch (Exception e) {
System.out.println("Error!");
input.next();// Move to next other wise exception
}
Before reading integer value you need to make sure scanner has one. And you will not need exception handling like that.
Scanner scanner = new Scanner(System.in);
int n1 = 0, n2 = 0;
boolean bError = true;
while (bError) {
if (scanner.hasNextInt())
n1 = scanner.nextInt();
else {
scanner.next();
continue;
}
if (scanner.hasNextInt())
n2 = scanner.nextInt();
else {
scanner.next();
continue;
}
bError = false;
}
System.out.println(n1);
System.out.println(n2);
Javadoc of Scanner
When a scanner throws an InputMismatchException, the scanner will not pass the token that caused the exception, so that it may be retrieved or skipped via some other method.
YOu can also try the following
do {
try {
System.out.println("Enter first num: ");
n1 = Integer.parseInt(input.next());
System.out.println("Enter second num: ");
n2 = Integer.parseInt(input.next());
nQuotient = n1/n2;
bError = false;
}
catch (Exception e) {
System.out.println("Error!");
input.reset();
}
} while (bError);
another option is to define Scanner input = new Scanner(System.in); inside the try block, this will create a new object each time you need to re-enter the values.
To follow debobroto das's answer you can also put after
input.reset();
input.next();
I had the same problem and when I tried this. It completely fixed it.
As the bError = false statement is never reached in the try block, and the statement is struck to the input taken, it keeps printing the error in infinite loop.
Try using it this way by using hasNextInt()
catch (Exception e) {
System.out.println("Error!");
input.hasNextInt();
}
Or try using nextLine() coupled with Integer.parseInt() for taking input....
Scanner scan = new Scanner(System.in);
int num1 = Integer.parseInt(scan.nextLine());
int num2 = Integer.parseInt(scan.nextLine());
To complement the AmitD answer:
Just copy/pasted your program and had this output:
Error!
Enter first num:
.... infinite times ....
As you can see, the instruction:
n1 = input.nextInt();
Is continuously throwing the Exception when your double number is entered, and that's because your stream is not cleared. To fix it, follow the AmitD answer.
#Limp, your answer is right, just use .nextLine() while reading the input. Sample code:
do {
try {
System.out.println("Enter first num: ");
n1 = Integer.parseInt(input.nextLine());
System.out.println("Enter second num: ");
n2 = Integer.parseInt(input.nextLine());
nQuotient = n1 / n2;
bError = false;
} catch (Exception e) {
System.out.println("Error!");
}
} while (bError);
System.out.printf("%d/%d = %d", n1, n2, nQuotient);
Read the description of why this problem was caused in the link below. Look for the answer I posted for the detail in this thread.
Java Homework user input issue
Ok, I will briefly describe it. When you read input using nextInt(), you just read the number part but the ENDLINE character was still on the stream. That was the main cause. Now look at the code above, all I did is read the whole line and parse it , it still throws the exception and work the way you were expecting it to work. Rest of your code works fine.

inputmismatchexception: entering into infinite loop? [duplicate]

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)
Closed 5 years ago.
I am facing java.util.InputMismatchException;
I catch InputMismatchException but I don't understand why it is going into infinite loop after taking first wrong input and the output goes on like this:
enter two integers
exception caught
this goes on repeating
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int flag = 0;
while (flag != 1) {
try {
System.out.println("enter two integers");
int a = sc.nextInt();
int b = sc.nextInt();
int result = a + b;
flag = 1;
System.out.println("ans is" + result);
} catch (NumberFormatException e) {
System.out.println("exception caught");
} catch (InputMismatchException e) {
System.out.println("exception caught");
}
}
}
You need to clear the buffer so that it is not invalid for nextInt() after the exception is thrown. Add a finally block and call sc.nextLine() within it:
while (flag != 1) {
try {
System.out.println("enter two integers");
int a = sc.nextInt();
int b = sc.nextInt();
int result = a + b;
flag = 1;
System.out.println("ans is" + result);
} catch (NumberFormatException e) {
System.out.println("exception caught");
} catch (InputMismatchException e) {
System.out.println("exception caught");
} finally { //Add this here
sc.nextLine();
}
}
Working example: https://ideone.com/57KtFw
If you press the enter key you need to consume this character too
int a = sc.nextInt();
int b = sc.nextInt();
sc.nextLine ();
then you can enter
2 3 <CR>
In your code you are catching InputMisMatchException and you are just printing a message which will result in again going to your while loop.
int a = sc.nextInt();
int b = sc.nextInt();
When either of these lines throw the exception your flag=1 will not be set and you will be in an infinite loop. Correct your exception handling and either break out of loop or clear your scanner input by reading it as string.

InputMismatchException in LOOP

I tried to find a solution for my problem, but couldn't find one that worked in practice. So please, if YOU'RE NOT SURE you know what the solution is, don't answer. I really need concrete help.
The problem is that when I run my simple code - you can pick a number and it's ok, loop is working fine. When you pick 0, it works too (run is finished), but when you put a letter or any string - there's a problem... an exception keeps looping without stop, even if I try inputting another value.
PS. I need to use Scanner here so please don`t write about readers etc. - just how to solve this specific problem.
Cheers,
Here's code (only main):
public static void main(String[] args) {
// TODO code application logic here
Scanner sc = new Scanner(System.in);
int dane = -1 ;
boolean keepLooping; //if you delete this works the same with same problem
do
{
keepLooping = false;
try
{
System.out.println("Pick a number:");
dane = sc.nextInt();
}catch (InputMismatchException e)
{
System.out.println("Your exception is: " + e);
keepLooping = false;
}
System.out.println("Out from exception");
}while ((dane != 0)||(keepLooping == true));
}
Try this:
public static void main(String[] args) {
// TODO code application logic here
Scanner sc = new Scanner(System.in);
int dane = -1 ;
boolean keepLooping = true; //if you delete this works the same with same problem
while(keepLooping && dane != 0)
{
System.out.println("Pick a number:");
try
{
dane = Integer.parseInt(sc.next());
}catch (NumberFormatException e)
{
keepLooping = true;
}
System.out.println("Out from exception");
}
Problem is when you say -
dane = sc.nextInt();
in the above line if you give an input of anything else than a number it will throw an exception input mismatch.
Lets understand what this line does. actually two things -
first sc.nextInt() reads an integer and only on successfull completion of this task it will assign that integer value to variable dane. but while reading an integer it throws an InputMismatchException so the assignment never happened and yet dane has it's previos value not the new one which scanner read so dane is still not equals to 0.
so the loop continues.
I hope it helps.
Edited
Do like this
public static void main(String[] args) {
// TODO code application logic here
Scanner sc = new Scanner(System.in);
int dane = -1 ;
boolean keepLooping; //if you delete this works the same with same problem
do
{
keepLooping = false;
try
{
System.out.println("Pick a number:");
dane = sc.nextInt();
}catch (InputMismatchException e)
{
System.out.println("Your exception is: " + e);
keepLooping = false;
dane = sc.nextInt();
}
System.out.println("Out from exception");
}while ((dane != 0)||(keepLooping == true)&&(dane!=0));
}

Validating Scanner input in Java [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
How do I stop my program from crashing when a non numeric value is entered? I'm aware of kbd.hasNextLong, but I'm unsure how to implement it.
This is how you can validate it :
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
boolean end = false;
long value;
while (end == false) {
try {
value = input.nextLong();
end = true;
} catch (InputMismatchException e) {
System.out.println("Please input the right LONG value!");
input.nextLine();
}
}
}
Note that input.nextLine() in catch-statement. If you type in some non-int text, it jumps into catch (cause Integer couldnt be read in nextInt), it printline message and then it goes again. But the value typed does NOT dissapiered so it crashes again even if you dont do anything.
The input.nextLine() "flushes" what you put in.
Using hasNextLong is other way (however I would prefer throwing an exception, because it IS an exception) :
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
boolean end = false;
long value;
while (end == false) {
if (input.hasNextLong()) {
value = input.nextLong();
end = true;
} else {
System.out.println("input the LONG value!");
input.nextLine();
}
}
}
A simple solution is to use exceptions.
int value;
do {
System.out.print("Type a number: ");
try {
value = kbd.nextInt();
break;
}
catch(InputMismatchException e) {
System.out.println("Wrong kind of input!");
kbd.nextLine();
}
}
while(true);

Java: Beginner using Scanner

I am learning Java and am learning I/O w/ java.util.Scanner. Specifically I am learning Scanner methods.
import java.util.Scanner;
public class ScannerTest {
public static void main(String args[]) {
Scanner s = new Scanner(System.in);
int result;
while (s.hasNextInt()) {
result += s.nextInt();
}
System.out.println("The total is " + result);
}
}
Because you're checking only
while (s.hasNextInt())
You could use try catch to catch the exception (see documentation here) you get when the program quits, so you can show your error message in the catch block without making the program close.
Perhaps you should try parsing each line:
public static void main(String args[]){
int sum = 0;
final Scanner scanner = new Scanner(System.in);
System.out.println("Enter a series of integers. Press 'q' to quit.");
while(true){
final String line = scanner.nextLine();
if(line.equals("q"))
break;
try{
final int number = Integer.parseInt(line);
sum += number;
}catch(Exception ex){
System.err.printf("Invalid: %s | Try again\n", ex.getMessage());
}
}
System.out.printf("The sum is %,d" , sum);
}
The idea is to read input line by line and attempt parsing their input as an integer. If an exception is thrown (meaning they entered an invalid integer) it would throw an exception in which you could handle in what ever way you want to. In the sample above, you are simply printing the error message and prompting the user to type in another number.
You can do this for the while loop (not tested though):
while (s.hasNextLine()) {
String line = s.nextLine();
int parsedInteger;
try {
parsedInteger = Integer.parseInt(line);
} catch(NumberFormatException numEx) {
if(line.startsWith("q")) break;
else {
System.out.println("please enter valid integer or the character 'q'.");
continue;
}
}
result += parsedInteger;
}
s.close();
Instead of scanning for int's you can scan for lines and then then parse each line as an int. I feel the advantage of this approach is that if any of your int's are malformed you can then handle them appropriately by say displaying an error message to the user.
OR, based on the answer by pinckerman, you can also do this.
while (s.hasNextInt()) {
try {
result += s.nextInt();
} catch(InputMismatchException numEx) {
break;
}
}
s.close();
A smart way you can do it and I've tried before is you use Integer.parseInt(String toParse); This returns an int and will reject all non numerical chars.
while (scanner.hasNextInt()) {
int i = Integer.parseInt(scanner.nextInt());
result += i;
if (result < 2147483648 && result > -2147483648) {
try{
throw new IndexOutOfBoundsException();
catch (Exception e) {e.printStackTrace();}
}
Try the following way:
int result = input.nextInt;
this will define your variable for result.
The only problem in your code is "not initializing" result. Once you initialized code will work properly. However, please do not forget you need to tell compiler EOF. Compiler can only understand the stop of the input on the console by EOF. CTRL Z is EOF for windows Eclipse IDE.

Categories

Resources