I am trying to figure out how to continue a code even after an exception is caught. Imagine that I have a text file filled with numbers. I want my program to read all those numbers. Now, lets say there is a letter mixed in there, is it possible for the exception to be caught, and then the code continues the loop? Would I need the Try and catches within a do-while loop? Please provide me with your ideas, I'd greatly appreciate it. I have provided my code just in case:
NewClass newInput = new NewClass();
infile2 = new File("GironEvent.dat");
try(Scanner fin = new Scanner (infile2)){
/** defines new variable linked to .dat file */
while(fin.hasNext())
{
/** inputs first string in line of file to variable inType */
inType2 = fin.next().charAt(0);
/** inputs first int in line of file to variable inAmount */
inAmount2 = fin.nextDouble();
/** calls instance method with two parameters */
newInput.donations(inType2, inAmount2);
/** count ticket increases */
count+=1;
}
fin.close();
}
catch (IllegalArgumentException ex) {
/** prints out error if exception is caught*/
System.out.println("Just caught an illegal argument exception. ");
return;
}
catch (FileNotFoundException e){
/** Outputs error if file cannot be opened. */
System.out.println("Failed to open file " + infile2 );
return;
}
Declare your try-catch block inside your loop, so that loop can continue in case of exception.
In your code, Scanner.nextDouble will throw InputMismatchException if the next token cannot be translated into a valid double value. That is that exception you would want to catch inside your loop.
Yes, I would put your try/catch in your while loop, although I think you'd need to remove your return statement.
Yep. These guys have it right. If you put your try-catch inside the loop, the exception will stay "inside" the loop. But the way you have it now, when an exception is thrown, the exception will "break out" of the loop and keep going until it reaches the try/catch block. Like so:
try while
^
|
while vs try
^ ^
| |
Exception thrown Exception thrown
In your case you want two try/catch blocks: one for opening the file (outside the loop), and another for reading the file (inside the loop).
If you want continue after catching exception:
Remove return statement when you encounter exception.
Catch all possible exceptions inside and outside while loop since your current catch block catches only 2 exceptions. Have a look at possible exceptions with Scanner API.
If you want to continue after any type of exception, catch one more generic Exception . If you want to exit in case of generic Exception, you can put return by catching it.
Related
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 :).
I have a program that reads in lines from a file (with two lines) using a while loop (condition is bufferedReader.readLine()!=null), assigns myJSONObject a JSON read from the file, then I have an if statment (if(bufferedReader.readLine()!=null&&!bufferedReader.readline.matches(DELETE_REGEX)) and if that's true (i.e. if the line we read is not null, and we don't match a regex) then perform some function on the JSON which should append that new JSON to a file.
I have this in some try-catch blocks. It looks a little like so:
try{
openFiles;
while(buff.readLine()!=null){
try {
instatiateAndUseJSONParser;
if(bufferedReader.readLine()!=null
&&!bufferedReader.readline.matches(DELETE_REGEX))
{doSomeStuff;}
else
{continue;}
} catch (AllTheExceptions e){e.printStackTrace}
}
closeFiles;
}catch(SomeMoreExceptions e){e.printStackTrace}
When I run this is gets to the iff statement, and then terminates with exit value:0 (program closed as normal)
Why is this? It doesn't get anywhere near the 'continue' or a catch block.
If I remove the second line I get a NullPointerException due to line 50 of String Reader, but I'm not using StringReader (I've tried importing it, but eclipse yellow-underlines it and this changes nothing). When debugging, it pops up a tab for StringReader.<init>(String) line: 50 and just says 'Source not found'.
I'm pretty new to Java, so I don't really have a clue what's happening. Any help would be appreciated in clearing this up.
Thanks!
Every time readLine() is called, it reads a new line. You can thus read 3 lines per iteration in your current code. You should assign the result of the first call to a variable, and use this variable:
String line = null;
while ((line = buff.readLine()) !=null) {
try {
instatiateAndUseJSONParser;
if (line.matches(DELETE_REGEX)) {
doSomeStuff;
}
}
catch (AllTheExceptions e){
throw new RuntimeException(e);
}
}
You should also avoid swallowing exceptions.
I'm trying to read a number for a switch case option but I'm stuck with an exception. I will try to explain the problem better in code:
do{
try{
loop=false;
int op=teclado.nextInt();
//I tryed a teclado.nextLine() here cause i saw in other Q but didn't work
}
catch(InputMismatchException ex){
System.out.println("Invalid character. Try again.");
loop=true;//At the catch bolck i change the loop value
}
}while(loop);//When loop is true it instantly go to the catch part over and over again and never ask for an int again
When I type an int it works perfectly, but the exception makes it start over. The second time, the program does not ask for the int (I think it could be a buffer and I need something like fflush(stdin) in C), and the buffer just starts writing like crazy.
You would be well-served creating a new instance of Scanner from within the catch to get the input should you fail. EDIT: You can use a Scanner.nextLine() to advance past the newline character when you fail. A do...while loop may be inappropriate for this, since it guarantees that it will execute at least once.
A construct that may help you out more is a simple while loop. This is actually a while-true-break type of loop, which breaks on valid input.
while(true) {
try {
op=teclado.nextInt();
break;
} catch(InputMismatchException ex){
System.out.println("Invalid character. Try again.");
teclado.nextLine();
}
}
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;
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