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のように異なる必要がある。