-2

OK, here's my problem. Our teacher wants us to create a program that creates a Fibonacci sequence and then the user can do operation with the array of numbers (like get number at an index, etc). I wanted to go above and beyond and idiot-proof it. I asked her about try/catch statements but she said that it was not in the curriculum.So, I did research and made this code:

while( valid ) {
        try {
            lengthOfSequence = keyboard.nextInt();
        } catch ( Exception e ) {
            out.println( "You entered an " + e + ". Please enter a number between 1 and " + maxLength );
            throw e;
        }
    }

(valid it true initially) So the code is supposed to get an integer that the user inputs. Then take that integer and assign it to lengthOfSequence. Running it properly (inputting an integer) will allow the code to run correctly, but when I plug in a "o" (or any other string) for my input, the catch is not catching the Exception and I get this error:

java.util.InputMismatchException
at java.util.Scanner.throwFor(Scanner.java:909)
at java.util.Scanner.next(Scanner.java:1530)
at java.util.Scanner.nextInt(Scanner.java:2160)
at java.util.Scanner.nextInt(Scanner.java:2119)
at FibonacciRunner.main(FibonacciRunner.java:28)

I've tried many ways to try to fix it including:lengthOfSequence = Integer.parseInt( keyboard.nextLine() ); which gives me

java.lang.NumberFormatException: For input string: "o"
at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
at java.lang.Integer.parseInt(Integer.java:492)
at java.lang.Integer.parseInt(Integer.java:527)
at FibonacciRunner.main(FibonacciRunner.java:29)

I've also tried naming the exception InputMismatchExceptionand NumberFormatException but still I get an error.

I'm a novice at coding and at Stack Overflow, so thank you in advance for the help

EDIT: I have tried removing the throw e but all that does is create an endless loop of the code outputting "You entered an java.util.InputMismatchException. Please enter a number between 1 and 101".

Also I removed this from the try statement because I thought it would not pertain to the question

 if( lengthOfSequence > 1 && lengthOfSequence < maxLength ) {
      fibonacci.createSequence( lengthOfSequence );
      valid = false;
 }
Aryan
  • 558
  • 4
  • 15
  • 4
    What do you think `throw e;` does? Why do you think so? – Sotirios Delimanolis Nov 20 '15 at 01:38
  • You are catching the Exception. But you are throwing another Exception. Remove `throw e` and let us know what happens – jiaweizhang Nov 20 '15 at 01:38
  • You are catching the exception but, throwing it back. The reason you get NumberFormatException is because you try to parse non-integer value to integer and InputMismatchException because nextInt() expects integer but, gets non-integer value. What do you wish to do after you catch the exception? – Raf Nov 20 '15 at 01:41
  • After you remove the `throw e;` statement, you will have an infinite loop because you never `break` from the loop or change the value of the `valid` variable. – Titus Nov 20 '15 at 01:43
  • removing the `throw e` just makes the catch statement loop and so my terminal is outputted with "You entered an java.util.InputMismatchException. Please enter a number between 1 and 101" repetedly – Aryan Nov 20 '15 at 02:07
  • @Titus oops, sorry about that. I removed `if( lengthOfSequence > 1 && lengthOfSequence < maxLength ) { fibonacci.createSequence( lengthOfSequence ); valid = false; }` from the try statement because it did not pertain to the question – Aryan Nov 20 '15 at 02:09
  • @Aryan to stop the loop when you receive bad input, you will have to consume that input in the `catch` block, you can do that by adding this statement in the `catch` block: `keyboard.next()` or `keyboard.nextLine()` – Titus Nov 20 '15 at 02:22
  • @Titus OMG, Thank you that worked. Want to post it and I'll mark it as an answer? – Aryan Nov 20 '15 at 02:27

3 Answers3

1

Change your code to:

boolean valid = false;
while( !valid ) {
    try {
        lengthOfSequence = keyboard.nextInt();
        valid = true;
    } catch ( Exception e ) {
        out.println( "You entered a wrong value. Please enter a number between 1 and " + maxLength);
    }
}

If you throw the exception, as you did in:

throw e;

Your program will no longer catch it and will suspend execution.

Gerardo Figueroa
  • 450
  • 1
  • 6
  • 16
0

Remove throw e;, that's all you need to do. You have already caught the exception in the catch clause, if you throw it then your calling method would have to catch it again. But since the calling method does not have a try-catch mechanism, program will terminate and give you UNCAUGHT EXCEPTION

Sotirios Delimanolis
  • 252,278
  • 54
  • 635
  • 683
Joel Min
  • 3,168
  • 1
  • 15
  • 35
  • 1
    What happens in the next loop iteration if they remove the rethrow? – Sotirios Delimanolis Nov 20 '15 at 01:56
  • The `throw e;` would have to be replaced with break or other mechanism to stop the loop. but that is not what the OP is asking. – Joel Min Nov 20 '15 at 02:00
  • bubbling up a stack trace is not a bad thing... you should always catch or log and display to user. – Chris Bolton Nov 20 '15 at 02:00
  • Your answer is currently trading one exception for another (in a sense, it's actually an infinite loop). That's not very useful imo. – Sotirios Delimanolis Nov 20 '15 at 02:01
  • Good catch by Sotirios. Just removing the `throe e` wont solve all problems. Take a look at this - http://stackoverflow.com/questions/3572160/how-to-handle-invalid-input-using-scanner-and-try-catch-currently-have-an-infin – Codebender Nov 20 '15 at 02:01
  • removing the 'throw e' just makes the catch statement loop and so my terminal is outputted with "You entered an java.util.InputMismatchException. Please enter a number between 1 and 101" repetedly – Aryan Nov 20 '15 at 02:06
  • I was hoping you'd address that. – Sotirios Delimanolis Nov 20 '15 at 02:12
  • Many people at SO tend to skip code that is not relevant to the problem (in order to provide a clear perspective for answerers), which is why I assumed OP had some kind of mechanism to change the value of `valid`. My answer was targeting the core issue of the code OP had (program terminating with uncaught exception), as for other sub-issues like infinite-loop, it is up to OP to figure out or re-ask the question. The key point of my answer is not "Remove `throw e;`", but the explanation that follows. Maybe I should have made that clear. – Joel Min Nov 20 '15 at 02:32
0

Titus answered my question as a comment but because I cant mark a comment as a question Ill just answer it myself:

This question is similar to: How to handle infinite loop caused by invalid input using Scanner

Quoting Titus:

to stop the loop when you receive bad input, you will have to consume that input in the catch block, you can do that by adding this statement in the catch block: keyboard.next() or keyboard.nextLine()

So I just added a keyboard.next(); to my catch block and removed the throw e and it stopped bugging out. Thank you guys!

Community
  • 1
  • 1
Aryan
  • 558
  • 4
  • 15