i'm writing a code in java, and i came across this error:
try {
//can't use the memberlist??
System.out.println("Login successful! Welcome back!");
member.memberProfile.setFirstName("Jane");
member.memberProfile.setLastName("Doe");
member.memberProfile.setAddress("123, Foster avenue, Chicago, US");
member.memberProfile.setPhone("7735249286");
member.memberProfile.setInterests("music");
System.out.println("Do you wish to change your user information? Please type 'yes' or 'no': ");
String choice= input.nextLine();
if(choice.equals("yes")){
member.memberProfile.Update_Details();
}
System.out.println("Your user information is: ");
System.out.print(member.memberProfile.toString());
} catch(UserNotFoundException | WrongAnswerException e ){
System.out.println(e.getMessage());
tries ++;
}
I have a problem with the line catch(UserNotFoundException | WrongAnswerException e )
It says i need to remove either UserNotFoundException or WrongAnswerException
When i do, it says i have to remove the entire catch block. What can i do?
If those are both checked exceptions (i.e. they aren't subclasses of RuntimeException) then the compiler will complain if none of the code in the try block throws those exceptions. It doesn't let you catch exceptions that static analysis shows are never thrown.
This is unrelated to the use of multi-catch | syntax.
Your doing a logical OR
break up the catch block
}catch(UserNotFoundException userNotFound ){
System.out.println(UserNotFound.getMessage());
tries ++;
}
}catch(WrongAnswerException wrongAnswer ){
System.out.println(wrongAnswer.getMessage());
tries ++;
}
Related
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.");
}
}
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 :).
Am working on a problem, basic code is shown below, takes 4 possible inputs from the user, and produces a response based on which one is input. However I need to add a test to validate that the only 1 of the 4 possible answers has been input.
I know how I could compare 2 of the 4 inputs however not all 4 at once, can someone give me an idea? Would prefer to figure out the actual code myself but a pointer in the right direction would be beneficial.
So to clarify How to - If input is anything except "Bill, Circular, Postcard or Letter" produce Error Message X
System.out.println("What type of Letter has been received?");
System.out.println("Bill, Circular, Postcard or Letter");
String Letter = kybd.nextLine();
{
if (Letter.equalsIgnoreCase("Bill"))
{
System.out.println("Bills must be paid");
}
else if (Letter.equalsIgnoreCase("Circular"))
{
System.out.println("Circulars are thrown away");
}
else if (Letter.equalsIgnoreCase("Postcard"))
{
System.out.println("Postcards are put on the wall");
}
else if (Letter.equalsIgnoreCase("Letter"))
{
System.out.println("Personal letters are read and have replies written for them");
}
}
if (Letter.equalsIgnoreCase("Bill"))
{
System.out.println("Bills must be paid");
}
else if (Letter.equalsIgnoreCase("Circular"))
{
System.out.println("Circulars are thrown away");
}
else if (Letter.equalsIgnoreCase("Postcard"))
{
System.out.println("Postcards are put on the wall");
}
else if (Letter.equalsIgnoreCase("Letter"))
{
System.out.println("Personal letters are read and have replies written for them");
}else{
System.out.println("ERROR");
}
You want to throw an 'else' conditional statement in there, and you may want to look at try and catch blocks, or simply 'throw' a NoSuchElement exception in your 'else' conditional.
Looking at this may be useful to you:
http://docs.oracle.com/javase/tutorial/essential/exceptions/throwing.html
Throwing an exception in an else statement would be a lot like the answer before mine, whereas a try...catch block is pretty much the test you're talking about. So, it could look something like this:
try
{
Letter != "Bill" //not exactly how it'd look, but this is a general idea on what you'd do here
}
catch (NoSuchElementException e)
{
System.out.println("Not a valid input.");
}
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.
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