【1】Javaの例外について
大きく分けて以下の通り。 ~~~~~~~~~~~~~ 1)Error 2)Exception / 検査例外 3)RuntimeException / 実行時例外 ~~~~~~~~~~~~~
1)Error
* 例外処理では復旧できない種類の例外クラス * OutOfMemory(メモリの不足)など
2)Exception / 検査例外
* 以下が必要(でないとコンパイルが通らない) ~~~~~~~~~~~~~ a) 必ずcatchブロックで例外をキャッチする or b) throws句で例外をメソッドの呼び出し元に投げる宣言をする ~~~~~~~~~~~~~
3)RuntimeException / 実行時例外
* キャッチする必要がない * 独自の例外クラスを作成する場合は、 RuntimeException を継承したほうがいいかも。
【2】使用上の注意
* 例外処理は遅い => 回避できるなら事前に回避した方がいい
例
int ParseValue(string targetValue) { try { // (a) ここで処理し時間が多少掛かる(これはしょうがない) return Integer.parseInt(targetValue); } catch (ArgumentNullException ex) { // (b) ここでも処理し時間が多少掛かる ((a)+(b)) return -1; } catch (NumberFormatException ex) { // (c) ここでも処理し時間が多少掛かる ((a)+(c)) return -1; } catch (Exception ex) { // (d) ここでも処理し時間が多少掛かる ((a)+(d)) return -1; } }
1)Tester-Doerパターン
* 処理(Doer, Do-er;やる人)を呼び出す前に、状態を判断(Tester)する方法 => .NETだと「TryParseパターン」ってもあるらしい
https://dobon.net/vb/dotnet/beginner/exceptionhandling.html#section9
サンプル
int ParseValue(string targetValue) { if (targetValue == null) { // Null の場合、ここだけで終わる return -1; } Integer.parseInt(targetValue); }
【3】クラス図
http://image.itmedia.co.jp/ait/articles/1111/01/r5fig1.png
【4】InterruptedException / 割り込み例外
* 割り込みが発生した場合に発生する例外 cf. Interrupt = 中断する
参考文献
API仕様
https://docs.oracle.com/javase/jp/6/api/java/lang/InterruptedException.html
例外全般
http://www.javaroad.jp/java_exception1.htm
http://www.atmarkit.co.jp/ait/articles/1111/01/news131.html
Exception / RuntimeException
http://www.nulab.co.jp/designPatterns/designPatterns4/designPatterns4-2.html
http://d.hatena.ne.jp/chiheisen/20090531/1243745909