When I run my simple code and enter char instead of integer value which was supposed to be Entered.
Program, listed below is supposed to be terminated after printing "error please Enter integer value".
But this code, also printing the line after Occurrence of error
import java.util.InputMismatchException;
import java.util.Scanner;
public class Test {
public static void main(String[] args) {
System.out.println("enter value integer ");
Scanner sn = new Scanner(System.in);
try{
int a = sn.nextInt();
} catch (InputMismatchException ex){
System.out.println("error please enter integer value");
}
System.out.println("not terminating");
}
}
But this code, also printing the line after Occurrence of error
Because it is out side of try-catch, that is the advantage of exception handling.
Exception handling prevents the abnormal termination of program due to run time error. And that is what happened.
See also
exception handing docs
It is terminating, it just prints out the System.out first. This is as expected - it jumps into the catch block, and then continues.
System.out.println("enter value integer ");
Scanner sn = new Scanner(System.in);
try {
int a = sn.nextInt();
} catch (InputMismatchException ex) {
System.out.println("error please enter integer value");
// you are catching input mis match here
// exception will catch and program continues
}
System.out.println("not terminating"); // this is out side the try-catch
So you will get this line in your out put too.
After entering the catch block, flow continues on, so the next line to execute is the bottom print.
If you want to terminate from within the catch:
try {
int a = sn.nextInt();
} catch (InputMismatchException ex) {
System.out.println("error please enter integer value");
return; // program will end
}
If you want it to be terminated you need to re-throw the exception e.g.:
System.out.println("enter value integer ");
Scanner sn = new Scanner(System.in);
try {
int a = sn.nextInt();
} catch (InputMismatchException ex) {
System.out.println("error please enter integer value");
throw new RuntimeException(ex);
}
System.out.println("not terminating"); // this is out side the try-catch
That way the last system output would not be printed and you would get a stacktrace instead.
Related
I'm trying to write a getInt() method, which abstracts the extraction of an integer from the console, to the rest of my program.
Inside, is a try using resource -- the resource being a scanner; with a catch block for the inevitable InputMismatchException.
It captures valid inputs, fine; and catches false inputs.
However, after -- recursively -- trying to again capture the input, my scanner instantly throws a NoSuchElementException, which is obviously linked to the last mismatch error.
Do I need to clear something in the second scanner, perhaps left from the first?
private static int getInt(String name) {
try (Scanner scanner = new Scanner(System.in)) {
System.out.printf("Enter %s: ", name);
return scanner.nextInt();
} catch (InputMismatchException e) {
System.out.println("Invalid");
return getInt(name);
}
}
I already tried to instantiate the scanner out of the function, like so:
Scanner scanner = new Scanner(System.in);
getInt(scanner, name);
...
private static int getInt(Scanner scanner, String name) {
try {
System.out.printf("Enter %s: ", name);
return scanner.nextInt();
} catch (InputMismatchException e) {
System.out.println("Invalid");
return getInt(scanner, name);
}
}
Here, I simply get a stack over flow error, because the mismatch error recurs.
I'm new to java but I've experimented a lot with this particular program and I've hit a wall. The purpose of this program is to catch if the user inputs a value exceeding the variable limit and also to validate that the input satisfies my specified range.
If the input exceeds the variable limit without a while loop, the program exits.
If the input exceeds the variable limit with a while loop, it loops infinitely.
I've tried using a while loop and my three outcomes are this:
The user inputs a programmer-specified valid number and all is well.
The user inputs a number above 100 and is prompted to try again...
The user exceeds the variable limit and the program goes into an
infinite loop.
If I put an escape in the catch block, it does the same as if the while was not there. I want the program to print the error but allow the user to retry a value.
while(!success){
try{
sh = sc.nextShort();
while(sh < 1 || sh > 100){
System.out.print("You must enter a value between 1-100: ");
sh = sc.nextShort();
} //close try
System.out.println("Great job!");
success = true; //escape the while
}catch{Exception ex){
System.out.println("ERROR: " + ex);
success = false; //causes infinite loop... I understand
} //close catch
} //close while
The problem is, that Scanner stores the whole input string and processes it.
When your input is not a short value but a string it throws an exception. You log the exception in the catch and in the next circle it tries to read a short value from the same stored string, which throws exception again .... -> infinite loop.
If you create a new Scanner in the catch, it will read again from the console:
while (!success) {
try {
sh = sc.nextShort();
while (sh < 1 || sh > 100) {
System.out.print("You must enter a value between 1-100: ");
sh = sc.nextShort();
} //close try
System.out.println("Great job!");
success = true; //escape the while
} catch (Exception ex) {
System.out.println("ERROR: " + ex);
sc = new Scanner(System.in);
} //close catch
}
As i understand your problem , you are facing a loop of exception on passing a bigger value (something bigger like e.g "10000000000").
you have the exceptions coming as below in infinite loop:
ERROR: java.util.InputMismatchException: For input string: "10000000000"
ERROR: java.util.InputMismatchException: For input string: "10000000000"
But you want program to print a exception line and then allow user to input again.
You can do that by below a way of reading bad input (String bad_input = sc.next();) from the scanner you used.
while (!success) {
try {
sh = sc.nextShort();
while (sh < 1 || sh > 100) {
System.out.print("You must enter a value between 1-100: ");
sh = sc.nextShort();
} // close try
System.out.println("Great job!");
success = true; // escape the while
} catch (Exception ex) {
System.out.println("ERROR: " + ex);
success = false; // causes infinite loop... I understand
String bad_input = sc.next();// your bad input to allow read that exception
} // close catch
} // close while
The cause of this problem can be found here:
If the translation is successful, the scanner advances past the input
that matched
If I understand your question correctly, you can get rid of your second while loop and replace it with an if. Then you can print out the value must be 1-100 and throw and exception to cause your program to go through the catch statement and print out the error you threw.
while(!success){
try{
sh = sc.nextShort();
if(sh < 1 || sh > 100){
System.out.print("You must enter a value between 1-100");
throw Exception;
} //close try
System.out.println("Great job!");
success = true; //escape the while
}catch{Exception ex){
System.out.println("ERROR: " + ex);
success = false; //causes infinite loop... I understand
} //close catch
} //close while
do {
try {
for(int i=c;i<no;i++){
System.out.println("enter barcode :");
isbn = input.next();
System.out.println("yearOfPub :");
yearOfPub = input.nextInt();}
loop =false;
}
catch (InvalidISBN_EXCEPTION e) {
// throw new InvalidISBN_EXCEPTION(isbn);
System.err.printf(" Error %s", e);
System.out.println("wrong ISBN");
loop = true;
}
} while(loop);
i have class store and class InvalidISBN_EXCEPTION
and i try to catch this error how i can fix it ?
Unless something in this code (your try block)
for(int i=c;i<no;i++){
System.out.println("enter barcode :");
isbn = input.next();
System.out.println("yearOfPub :");
yearOfPub = input.nextInt();}
loop =false;
declares that it will throw a checked Exception of type InvalidISBN_EXCEPTION, the compiler will complain. You are saying you can catch that error but nothing ever declares it will throw it. You have to remove the try/catch code around the code.
My program is not compiling and showing me this error:
System.out.println("Error: "+ e.getMessage());
Scanner scanner = new Scanner(System.in);
try {
int num = scanner.nextInt();
if (num != 0) {
throw new Exception("Not zero");
}
System.out.println("I'm happy with the input.");
} catch (InputMismatchException e) //InputMismatchException is never thrown in body of corresponding try statement
{
System.out.println("Invalid Entry");
} catch (Exception e) {
System.out.println("Error: "+ e.getMessage());
}
The error message is quite clear:
InputMismatchException is never thrown in body of corresponding try statement
You're trying to catch an exception which is guaranteed not to be thrown from the try block. This is useless, and even invalid. Remove the catch (InputMismatchException e) block.
Actually, the try block can throw a java.util.InputMismatchException. So I guess that you're in fact catching an InputMismatchException of another package. Check your imports, and make sure you import java.util.InputMismatchException and not some other com.foo.bar.InputMismatchException.
EDIT:
the error message confirms what I thought. You're catching javaapplication9.InputMismatchException, instead of java.util.InputMismatchException. I'm not sure why you defined your own InputMismatchException.
I'm trying to throw an exception (without using a try catch block) and my program finishes right after the exception is thrown. Is there a way that after I throw the exception, to then continue execution of my program? I throw the InvalidEmployeeTypeException which I've defined in another class but I'd like the program to continue after this is thrown.
private void getData() throws InvalidEmployeeTypeException{
System.out.println("Enter filename: ");
Scanner prompt = new Scanner(System.in);
inp = prompt.nextLine();
File inFile = new File(inp);
try {
input = new Scanner(inFile);
} catch (FileNotFoundException ex) {
ex.printStackTrace();
System.exit(1);
}
String type, name;
int year, salary, hours;
double wage;
Employee e = null;
while(input.hasNext()) {
try{
type = input.next();
name = input.next();
year = input.nextInt();
if (type.equalsIgnoreCase("manager") || type.equalsIgnoreCase("staff")) {
salary = input.nextInt();
if (type.equalsIgnoreCase("manager")) {
e = new Manager(name, year, salary);
}
else {
e = new Staff(name, year, salary);
}
}
else if (type.equalsIgnoreCase("fulltime") || type.equalsIgnoreCase("parttime")) {
hours = input.nextInt();
wage = input.nextDouble();
if (type.equalsIgnoreCase("fulltime")) {
e = new FullTime(name, year, hours, wage);
}
else {
e = new PartTime(name, year, hours, wage);
}
}
else {
throw new InvalidEmployeeTypeException();
input.nextLine();
continue;
}
} catch(InputMismatchException ex)
{
System.out.println("** Error: Invalid input **");
input.nextLine();
continue;
}
//catch(InvalidEmployeeTypeException ex)
//{
//}
employees.add(e);
}
}
If you throw the exception, the method execution will stop and the exception is thrown to the caller method. throw always interrupt the execution flow of the current method. a try/catch block is something you could write when you call a method that may throw an exception, but throwing an exception just means that method execution is terminated due to an abnormal condition, and the exception notifies the caller method of that condition.
Find this tutorial about exception and how they work - http://docs.oracle.com/javase/tutorial/essential/exceptions/
Try this:
try
{
throw new InvalidEmployeeTypeException();
input.nextLine();
}
catch(InvalidEmployeeTypeException ex)
{
//do error handling
}
continue;
If you have a method that you want to throw an error but you want to do some cleanup in your method beforehand you can put the code that will throw the exception inside a try block, then put the cleanup in the catch block, then throw the error.
try {
//Dangerous code: could throw an error
} catch (Exception e) {
//Cleanup: make sure that this methods variables and such are in the desired state
throw e;
}
This way the try/catch block is not actually handling the error but it gives you time to do stuff before the method terminates and still ensures that the error is passed on to the caller.
An example of this would be if a variable changed in the method then that variable was the cause of an error. It may be desirable to revert the variable.