INvalid input exception - java

I have a menu which reads integers for input ,here is the method for the menu:
public int menu(String _menuHeader,String[] _menuItems) throws InvalidInputException {
int choice = 0;
do {
try {
scanner.nextLine();
System.out.println(_menuHeader);
for (int i = 0; i < _menuItems.length; i++) {
System.out.println(" " + (i + 1) + " " + _menuItems[i]);
}
choice = scanner.nextInt();
if (choice <= 0 || choice > _menuItems.length) {
throw new InvalidInputException();
}
} catch (Exception e) {
System.out.println("Enter valid input");
validInput = false;
} catch (InvalidInputException e) {
System.out.println("Please enter a choice between 1 and" + _menuItems.length);
validInput = false;
}
} while (!validInput);
}
Now I want to catch a exception when the input is out of bound of the allowed choices, i.e input 7 for choices 1 and 2,
For this I have tried using InvalidInputException, but this gives a an compile error as 'cannot find symbol InvalidInoutException' although I have imported 'import.java.Throwable/Exception;'

Do you have a custom exception class defined for your "InvalidInputException"?. If not please go through this post for creating custom exception classes.
How to define custom exception class in Java, the easiest way?

There is not such thing as InvalidInputException in java.lang. You will have to create your own custom exception, and name it as you wish.
Sorry to say this, but judging from your code you have poor knowledge of how the exception handling works in Java. If this is exception practice, then refactor your code accordingly. If not, don't use exceptions at all. You don't need them in this snippet of code.

I didn't look up the import, but the problem is that you catch Exception before InvalidInputException. Java uses the first matching catch to handle an exception, so if you catch a superclass in front of any of its subclasses, the subclass catches will never occur.
Reverse the order of your catches and you'll have better luck.
Edit: OK, I did look it up and Scanner.nextInt() doesn't throw that exception anyway. You probably want java.util.InputMismatchException, but check for yourself:
http://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html#nextInt%28%29
PS: This really isn't the best way to handle invalid input, by the way. The Scanner class has a hasNextInt() method to detect whether a valid integer is next in the input stream or not. As a rule, it's generally better to avoid throwing and catching exceptions if there's a sensible alternative. The Scanner hasNext* methods are specifically designed to give you those sensible alternatives.

Related

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 :).

Get an input from user scanner class

normally when I get a user interaction from a keyboard I use class scanner to do so but the problem I noticed when using its methods is that it's not handling exception! For example
Scanner input = new scanner();
Int number = input.nextInt();
The above works good for all integer numbers but if the user mistakly entered a character or a string, it will throw an exception and stops executing the rest of the program.
My question is there any way to avoid this?
Thank you in advance.
Try to catch the exception. Or use the hasNextInt method to prevent the exception from being thrown in the first place.
try {
int number = input.nextInt();
} catch (InputMismatchException e) {
System.out.println("That wasn't a number!");
}
Perhaps you should catch the exception and ask the user again?
See http://www.functionx.com/java/Lesson14.htm for exactly your problem.

check the input null

i've found this line of code got error if the input not an number
int sum = Integer.parseInt(request.getParameter("sum"));
the error message is
type Exception report
message
descriptionThe server encountered an internal error () that prevented it from fulfilling this request.
exception
org.apache.jasper.JasperException: java.lang.NumberFormatException: For input string: "a"
root cause
java.lang.NumberFormatException: For input string: "a"
how to handle the input if the input is a string or null?
thanks
You should first make sure request parameter is not null and contains numbers only using:
if (request.getParameter("sum") != null &&
request.getParameter("sum").matches("^\\d+$"))
int sum = Integer.parseInt(request.getParameter("sum"));
Try:
int sum = 0;
try {
sum = Integer.parseInt(request.getParameter("sum"));
}
catch (NumberFormatException e) {
// sum = 0. If you needed to do anything else for invalid input
// put it here.
}
It really depends on what should be done if sum is not a number.
try{
int sum = Integer.parseInt(request.getParameter("sum"));
}
catch(Exception e)
{
//how do you want to handle it? like ask the user to re-enter the values
}
Just catch the exception and handle it accordingly:
int sum;
try {
sum = Integer.parseInt(request.getParameter("sum"));
}
catch {
//do something if invalid sum
}
Check manually (loop over the characters)
Catch the exception
Try this:
try {
sum = Integer.parseInt(request.getParameter("sum"));
} catch (NumberFormatException e) {
... // handle if the string isn't a number
} catch (NullPointerException e) {
... // handle if it's null
}
Check for null before Using Intefer.parseInt and also you can check whether input contains other than numeric value
Here's a different approach that doesn't involve throwing and catching exceptions:
String input = request.getParameter("sum");
// Validate the input using regex
if (input == null || !input.matches("^-?\\d{1,8}$")) {
// handle bad input, eg throw exception or whatever you like
}
int sum = Integer.parseInt(input);
Note that this regex doesn't allow numbers too large, and allows negative numbers
I see the org.apache.jasper.JasperException Which means this is in a JSP? If you're adding code like that to a JSP, you might want to reconsider what you're doing. Ideally, you should handle things like input validation in a controller of some sort, and then pass off results to a template of JSP for rendering.
There are many frameworks out there to help with this sort of thing, and in general they're worth using because your web application will benefit from all of the work that the framework authors have already done in the realm of security etc...
Pretty much any of the half a dozen code answers already posted will work for you though if you just want to hack it out.

how to catch a NoSuchElementException?

My class assignment is to write a program that has the user input a set of numerical values. If the user enters a value that is not a number, the program is supposed to give the user 2 second chances to enter a number correctly, and after those two chances, quit asking for input and print the sum of all values entered correctly so far.
As is, my code doesn't work quite right. When the first non-number is entered, the program executes the code in the catch block once, prints the "gimme input" line at the beginning of the try block but then immediately executes the code in the catch block again without waiting for the user to enter another number.
While perusing my textbook for clues, I noticed this line: "A NoSuchElementException is not caught by any of the catch clauses. The exception remains thrown until it is caught by another try block or the main method terminates."
Which is great, because now at least I know there's a good reason this is happening, but my textbook doesn't contain any further information on this quirk, and I haven't been able to find any understandable answers via StackOverflow or Google. So my question is two part:
a) How should I get around this for the purposes of this assignment?
b) What exactly does it mean that the exception is not caught by a catch clause? Isn't that what catch clauses exist for? I do want a solution to my assignment, but I also want to understand why this is the way it is, if possible.
Thanks for any help!
import java.util.InputMismatchException;
import java.util.NoSuchElementException;
import java.util.ArrayList;
import java.util.Scanner;
public class NotANumber {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("This program computes the sum of any number of real numbers. When you are done entering values, enter something other than a real number twice in a row.\n");
ArrayList<Double> numbers = new ArrayList<Double>();
int count = 0;
while (count < 2) {
try {
System.out.println("Please enter a floating point number: ");
double newNumber = in.nextDouble();
numbers.add(newNumber);
count = 0;
}
catch (NoSuchElementException exception) {
System.out.println("The value entered was not correctly specified. All values must be integers or floating point values.");
count++;
}
}
if (!numbers.isEmpty()) {
double sum = 0;
for (Double each : numbers) {
sum = sum + each;
}
System.out.println("The sum is " + sum);
}
else {
System.out.println("There is no sum as no correctly specified values were entered.");
}
}
}
For now, forget about catching the exception (it isn't what you want to do!). What you want to do is add calls like: s.hasDouble() before calling s.nextDouble().
The reason you don't want to catch that exception is because it is a RuntimeException which is meant to be used to indicate a programmer mistake, one that you should fix.
The simple advice is don't catch exceptions that the compiler doesn't tell you to catch, instead if one of them is thrown figure out the change you need to make to your code so that exception doesn't happen.
For exceptions the compiler tells you that you must deal with them you do something like:
try
{
foo();
}
catch(final IOException ex)
{
// do something smarter here!
ex.printStackTrace();
}
In that code, foo() is declared something like:
public void foo()
throws IOException
{
// ... code ...
}
IOException is a checked exception (RuntimeException, also called unchecked exceptions, should not be caught, checked exceptions must be caught... well you can do other things beyond catch, but for now don't worry about those).
So, long answer short, make the exception not happen by calling s.hasXXX() before calling s.nextXXX().
You are mistaken: Scanner.nextDouble throws a NoSuchElementException if the input is exhausted, which is unlikely to happen with standard input (it will block instead). An incorrect value will produce an InputMismatchException.
My guess, however, is that nextDouble does not remove the offending value from the stream on failure. You'll need to "clear" the input in your catch before resuming the read.
#TofuBear states:
The simple advice is don't catch exceptions that the compiler doesn't tell you to catch, instead if one of them is thrown figure out the change you need to make to your code so that exception doesn't happen.
I think that's an over-simplification.
It is true that exceptions that are declared as checked exceptions HAVE to be either caught or declared as thrown in the method signature.
It is also true that you don't have to catch unchecked exceptions, and indeed that you should think carefully about whether it wise to catch an unchecked. (For instance, you should think whether the exception is being thrown at the point you expect and for the reasons that you expect.)
However, in some circumstances it is clearly necessary to catch them. For instance:
try {
System.out.println("Enter a lucky number!");
String input = // get string from user
int number = Integer.parseInt(input);
...
} catch (NumberFormatException ex) {
System.err.println("Bad luck! You entered an invalid number");
}
If you didn't catch NumberFormatException ... which is an unchecked exception ... then you wouldn't be in position to print out a friendly message, and ask the user to try again.
In short, unchecked exceptions don't always mean programmer error.
A few of the standard ones could indicate bad input from a user or client (e.g. NumberFormatException, IllegalArgumentException, ArithmeticException, etc), or they could indicate something that a specific application can recover from, or at least attempt to diagnose.
I've come across third party libraries where the designer has an aversion to checked exceptions and has declared all library exceptions as unchecked. (Bad design IMO, but it happens ...)
So a blanket statement that you shouldn't catch unchecked exceptions is clearly wrong advice.
However the second part of #TofuBear's advice is valid. It is (generally) a better idea to do a test to prevent an anticipated exception from happening than to do the action and catch the exception. (The code is typically simpler, and typically more efficient ... though there are counter examples.)
In this case, if you call and test hasNextDouble() before nextDouble() you can avoid the error case you are trying to handle with the try / catch.
surround your statements around try..catch is a good idea when you have no clue that what will happen in real scenario. but i have alternative solution, most of the time we know this exception raise so you can avoid it using implementing iterator as follows..
for (ListIterator<Double> iter = numbers.listIterator(); iter.hasNext(); ) {
if(iter.hasNext()) { // this return false in case of NoSuchElementException
// do your stuff here
}
}
You must change import.
Instead of
import java.util.NoSuchElementException;
use
import org.openqa.selenium.NoSuchElementException;

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