Javaにおけるデータ型と例外処理
Jim White
Java Developer
Error は重大な問題import java.util.*;
public class CauseOutOfMemory {
public static void main(String[] args) {
List<Long> numbers = new ArrayList<Long>();
long counter = 0;
while (true) {
numbers.add(counter);
counter++;
}
}
}
Exception in thread "main" java.lang.OutOfMemoryError: Java heap space
at java.base/java.lang.Long.valueOf(Long.java:1204)
at foo/exceptions.CauseOutOfMemory.main(CauseOutOfMemory.java:12)
| チェック例外 | 実行時(「非チェック」)例外 | |
|---|---|---|
| 処理の必須性 | 必須 | 不要 |
| 一般的原因 | 制御不能な事象 | プログラミングミス |
| 回復 | 想定していれば回復可能 | 通常は回復困難 |
| 対処法 | try/catch または throws | 回避するよう注意してコーディング |
| 例 | ファイル未発見 | 配列の範囲外アクセス |
RuntimeException のサブクラスでない Exception のサブクラスは「チェック例外」FileNotFoundException)RuntimeException は全「非チェック例外」のスーパークラスIndexOutOfBoundsException)ArithmeticException)| RuntimeException のサブクラス | 送出される状況 |
|---|---|
| ArithmeticException | 0 での除算など不正な算術計算 |
| IndexOutOfBoundsException | 配列や文字列などのインデックスが範囲外 |
| NegativeArraySizeException | 負のサイズで配列を作成しようとした |
int y = 5/0; // ArithmeticException を発生させるコード
int[] list = new int[-1]; // NegativeArraySizeException を発生させるコード
Exception in thread "main" java.lang.ArithmeticException: / by zero
Exception in thread "main" java.lang.NegativeArraySizeException: -1
public class LoadClass {
public static void main(String[] args) {
Class myClass = Class.forName("com.mysql.Driver");
}
}
LoadClass.java:3: error: unreported exception ClassNotFoundException;
must be caught or declared to be thrown
Class myClass = Class.forName("com.mysql.Driver");
^
1 error
Javaにおけるデータ型と例外処理