例外処理: エラー対応

try-catch-finally。リソースは try-with-resources。

try-catch
例外を捕捉。
throw
例外をスロー。
finally
必ず実行されるブロック。
セーフティネット (Safety Net)

例外処理は「サーカスのセーフティネット」です。 **try** = 空中ブランコに挑戦する **catch** = 落ちた時にネットが受け止める **finally** = 成功しても失敗しても拍手 ネットがないと、落下(アプリクラッシュ)します。

例外処理

try-catch
// try-catch
try {
int result = 10 / 0;
} catch (ArithmeticException e) {
System.out.println("Cannot divide by zero");
} finally {
System.out.println("Always executed");
}
// 例外をスロー
public void withdraw(int amount) throws InsufficientFundsException {
if (amount > balance) {
throw new InsufficientFundsException("Not enough money");
}
balance -= amount;
}
// 複数の例外をキャッチ
try {
// ...
} catch (IOException | SQLException e) {
e.printStackTrace();
}
実行結果
Cannot divide by zero\nAlways executed
Bad
// ❌ Bad: 例外を握りつぶす
try {
riskyOperation();
} catch (Exception e) {
// 何もしない(最悪)
}
Good
// ✅ Good: 適切に処理
try {
riskyOperation();
} catch (SpecificException e) {
logger.error("Operation failed", e);
throw new RuntimeException(e);
}

パターン

try-with-resources, Custom
// try-with-resources(自動クローズ)
try (BufferedReader reader = new BufferedReader(
new FileReader("file.txt"))) {
String line = reader.readLine();
} catch (IOException e) {
e.printStackTrace();
}
// reader は自動的に閉じられる
// カスタム例外
public class UserNotFoundException extends RuntimeException {
public UserNotFoundException(String userId) {
super("User not found: " + userId);
}
}
// チェック例外 vs 非チェック例外
// チェック例外: IOException, SQLException(宣言必須)
// 非チェック例外: RuntimeException(宣言不要)
// Optional で null を避ける
Optional<User> user = findUser(id);
user.orElseThrow(() -> new UserNotFoundException(id));
Tip: 例外を握りつぶさない。ログを残すか再スロー。

合格ライン

try-with-resources を使える
カスタム例外を作れる
チェック例外と非チェック例外の違いを説明できる

参考リンク

演習課題

課題1: try-catch
ファイル読み込みで IOException をキャッチしてください。
課題2: マルチキャッチ
複数の例外を1つの catch ブロックで処理してください。

次のステップ