実行は例外がキャッチされた場合でも終了します

サミールSiddiqui著:

私は、Javaの例外処理を学ぶために、簡単な電卓アプリを実行していました。InputMismatchExceptionとはArithmeticExceptionを区分するためにゼロで:私が処理される2つの例外を設定しました。

ArithmeticExceptionは取り扱ってみませんか-whileループは継続されます。しかしInputMismatchExceptionをキャッチした後、実行はループを続けるのではなく、終了します。

コード:

do {
  result = 0;
  System.out.println("Enter the expression to calculate: (eg: 4 + 5) \n");
  try {
    num1 = input.nextInt();
    op = input.next().charAt(0);
    num2 = input.nextInt();
    result = a.Calc(num1, op, num2);             //Calc function to calculate
    System.out.println("= " + result);
  } catch (InputMismatchException e) {
     System.err.println("Please space out the expression");
  } catch (ArithmeticException e) {
     System.err.println("Cannot divide by zero");
  }
  System.out.println("Do you want to try again? (Y to retry)");
  OP = input.next().charAt(0);
} while (OP == 'Y' || OP == 'y');

出力:

Enter the expression to calculate: (eg: 4 + 5)
4 / 0
Cannot divide by zero                  //Exception handled
Do you want to try again? (Y to retry)
Y                                      //Do-while continues

Enter the question to calculate: (eg: 4 + 5)
4+5
Please space out the expression        //Exception handled
Do you want to try again? (Y to retry) //Rest of the code is executed
                                       //But the execution also terminates

予想:DO-ながらInputMismatchException後も継続します

これは、これを行うための正しい方法は何ですか?

アンドレアス:

InputMismatchException呼び出しによって引き起こされるnextInt()次のトークンがあるので、4+5

トークンはされて消費されない失敗したコールで。

ことを意味しているOP = input.next().charAt(0)セットOP = '4'、あなたがあれば非常に明らかであるべきである何かデバッグコードを。参照してください。デバッガは何とどのようにそれは私が問題の診断に役立つことができますか?そして、小さなプログラムをデバッグする方法

あなたは呼び出すことで例えば、失敗したトークン(複数可)を破棄するために必要nextLine()catch句:

} catch (InputMismatchException e) {
    System.err.println("Please space out the expression");
    input.nextLine(); // Discard input(s)
} ...

おすすめ

転載: http://43.154.161.224:23101/article/api/json?id=333086&siteId=1