study-note

例外処理

目次

概要

基本構文

try-catch-finally

try {
	// 例外が発生する可能性のある処理
} catch (例外名 変数名) {
	// 例外発生時の処理
} finally {
	// 必ず実行される処理
}

例外クラス

Throwable
 ├─ Error
 └─ Exception
     ├─ RuntimeException
     └─ (その他)

検査例外/非検査例外

検査例外(checked exception)

非検査例外(unchecked exception)

構文例

基本構文

try {
  処理;
} catch (IOException e) {
  処理A;
} catch (Exception e) {
  処理B;
}

マルチcatch

catch (IOException | SQLException e) {
  処理;
}

finallyブロック

throws句

void f() throws IOException {
	処理;
}

throw文

throw new IllegalArgumentException("message");

独自例外クラス

class MyException extends Exception {
	MyException(String msg) {
		super(msg);
	}
}

try-with-resources

try (Resource r = new Resource()) {
	処理;
}