Bifalgorithm post · Computer science one · Catching Exceptions

How can Java handle different exception types with multiple catch blocks?

How can Java handle different exception types with multiple catch blocks? (Computer science one · Catching Exceptions) — "The code above could have resulted in…

Ideas in this flowchart

  • Javaは複数のcatchブロックで異なる例外を処理できる。
  • tryブロックは標準入力からトークンを読み取り、整数へ変換する。
  • 発生した例外の種類に応じて、実行されるcatchブロックが決まる。
  • NumberFormatExceptionでは、入力データが無効だと表示してプログラムを終了する。
  • NoSuchElementExceptionでは、入力の読み取り失敗を表示し、nにデフォルト値20を設定する。
  • Exceptionでは、一般的な例外の発生を表示し、スタックトレースを出力して終了する。
  • 各catchブロックは異なる種類の例外を捕捉する。
  • そのため、例外を保持する変数名はnfe、nsee、eのように異なる必要がある。
Feed/

How can Java handle different exception types with multiple catch blocks?

No cover

Channel

Computer science one

1 page

"The code above could have resulted in other exceptions. For example if the Scanner had failed to read the next token from the standard input, it would have thrown a NoSuchElementException. We can add as many catch blocks as we want to handle each exception differently.\n\nScanner s = new Scanner(System.in);\n\nint n = 0;\n\ntry {\n\nString input = s.next();\n\nn = Integer.parseInt(input);\n\n} catch (NumberFormatException nfe) {\n\nSystem.err.println(\"You entered invalid data!\");\n\nSystem.exit(1);\n\n} catch (NoSuchElementException nsee) {\n\nSystem.err.println(\"Input reading failed, using default...\");\n\nn = 20; //a default value\n\n} catch(Exception e) {\n\nSystem.err.println(\"A general exception occurred\");\n\ne.printStackTrace();\n\nSystem.exit(1);\n\n}\n\nEach catch block catches a different type of exception. Thus, the name of the variable that holds each exception must be different in the chain of catch blocks; nfe, nsee, e."

Flowchart preview
👍
0
0 comments0 shares

Sign in to view and post comments.