例外処理とは
プログラム実行途中で発生した想定外の結果を例外(Exception) といい、その記述したコードを例外処理(エラーハンドリング) といいます。
正常系と異常系
例外といっても、さまざまな種類があります。
- メモリ不足
- 外部ファイルが読み込めない
- 変数がNullになった
- 計算処理できない
これら例外は大きく2つの種別にわけられます。
- 正常系
- 異常系(例外)
正常系
例えば数値の割り算で、割る数が「0」のときは例外ArithmeticExceptionが発生します。
int score = 100;
int count = 0;
//エラーが発生
float answer = score / count;
例外の回避
この処理は変数countが「0」にならなければ、例外となりません。
int score = 100;
int count = 0;
float answer = 0;
// if文で回避
if (count > 0) {
answer = score / count;
} else {
System.out.println("個数が間違っています。");
}
異常系
異常系は予期せないエラー発生し、プログラムを強制終了させないために例外処理をするケースです。
例外処理の構造
Javaの例外処理は、Throwableをスーパークラスとして、ErrorクラスとExceptionクラスにわけられます。
Throwableクラス
Throwableは、Javaのすべてのエラーと例外をスーパークラスで、Throw(投げる)からきています。
Error
Errorはメモリ不足(OutOfMemoryError)や、スタック領域のオーバーフロー(StackOverflowError)など、ハード的な致命的エラーなどで発生します。
Exception
Exceptionは、検査例外(Checked Exception)と非検査例外(Unchecked Exception)」にわけられ、例外が発生しても例外処理で回避できます。Exceptionは何かしら対処しなければコンパイルエラーになります。
RuntimeException
非検査例外にはRuntimeExceptionがあり、プログラム実行時に発生および対処できる例外です。
例外処理の方法
ファイル構成
sample/
└── ExceptionApp.java
平均の計算
平均を計算するcalculateAverage() メソッドを作成します。
package sample;
public class Exception {
public static void main(String[] args) {
int score = 100;
int count = 0;
float average = 0;
average = calculateAverage(score, count);
System.out.println(average);
}
public static float calculateAverage(int score, int count) {
return score / count;
}
}
RuntimeExceptionの発生
このプログラムを実行するとArithmeticExceptionが発生します。
RuntimeExceptionの対処
ArithmeticExceptionはRuntimeExceptionなので、if文などのプログラムで対処でます。
public static float calculateAverage(int score, int count) {
if (count > 0) {
return score / count;
} else {
System.out.println("個数が間違っています。");
return 0;
}
}
検査例外(Exception)
RuntimeExceptionは非検査例外ですが、通常のException(検査例外)をみてみましょう。
FileReader
Javaでファイル読み込みをするには、FileReaderクラスを利用します。
FileReader インスタンス = new FileReader(ファイルパス);
FileReaderでファイルを読み込むメソッドを定義してみましょう。
public static void loadFile(String path) {
FileReader reader = new FileReader(path);
}
Exception処理が必須
FileReaderクラスではファイルが存在しないときの例外FileNotFoundExceptionが必須なので、コンパイルエラーになります。検査例外を扱うには、例外処理の構文で対処します。
演習
問題1
エラー、例外のスーパークラスはどれですか?
- Throwable
- Error
- Exception
- RuntimeException
問題2
エラークラスはどれですか?
- Throwable
- Error
- Exception
- RuntimeException
問題3
非検査例外(Unchecked Exception)クラスはどれですか?
- Throwable
- Error
- Exception
- RuntimeException
問題4
検査例外(Checked Exception)クラスはどれですか?
- Throwable
- Error
- Exception
- RuntimeException
コース内レッスン
- 1
Lesson 1
Javaとは
レッスンを見る - 2
Lesson 2
環境構築
レッスンを見る - 3
Lesson 3
プロジェクト作成と実行
レッスンを見る - 4
Lesson 4
Javaの基本とクラス
レッスンを見る - 5
Lesson 5
パッケージ
レッスンを見る - 6
Lesson 6
変数
レッスンを見る - 7
Lesson 7
データ型
レッスンを見る - 8
Lesson 8
演算
レッスンを見る - 9
Lesson 9
論理演算
レッスンを見る - 10
Lesson 10
条件分岐
レッスンを見る - 11
Lesson 11
配列
レッスンを見る - 12
Lesson 12
繰り返し(for)
レッスンを見る - 13
Lesson 13
繰り返し(while)
レッスンを見る - 14
Lesson 14
staticメソッド
レッスンを見る - 15
Lesson 15
オブジェクト指向とクラス
レッスンを見る - 16
Lesson 16
フィールド
レッスンを見る - 17
Lesson 17
インスタンスメソッド
レッスンを見る - 18
Lesson 18
コンストラクタ
レッスンを見る - 19
Lesson 19
継承
レッスンを見る - 20
Lesson 20
ポリモーフィズム
レッスンを見る - 21
Lesson 21
Collection
レッスンを見る - 22
Lesson 22
Map
レッスンを見る - 23
Lesson 23
イテレータ
レッスンを見る - 24
Lesson 24
アクセス修飾子
レッスンを見る - 25
Lesson 25
カプセル化
レッスンを見る - 26
Lesson 26
抽象クラス
レッスンを見る - 27
Lesson 27
インターフェイス
レッスンを見る - 28
Lesson 28
Enum
レッスンを見る - 29
Lesson 29
例外処理
レッスンを見る - 30
Lesson 30
エラーハンドリング
レッスンを見る - 31
Lesson 31
CSVファイル操作
レッスンを見る - 32
Lesson 32
Thread
レッスンを見る - 33
Lesson 33
ラムダ式
レッスンを見る - 34
Lesson 34
タイマー処理
レッスンを見る