Execution terminates even when exception is caught

前端 未结 1 773
南旧
南旧 2020-12-22 01:10

I was running a simple Calculator app to learn Java\'s exception handling. I\'ve set two exceptions to be handled: InputMismatchException and ArithmeticException for divisio

相关标签:
1条回答
  • 2020-12-22 01:30

    InputMismatchException is caused by the call to nextInt(), because the next token is 4+5.

    The token is not consumed by the failed call.

    Which means that OP = input.next().charAt(0) sets OP = '4', something that should be very apparent if you debugged the code. See What is a debugger and how can it help me diagnose problems? and How to debug small programs.

    You need to discard the failed token(s), e.g. by calling nextLine() in the catch clause:

    } catch (InputMismatchException e) {
        System.err.println("Please space out the expression");
        input.nextLine(); // Discard input(s)
    } ...
    
    0 讨论(0)
提交回复
热议问题