例外処理: エラー対応
try-catch-finally。リソースは try-with-resources。
try-catch
例外を捕捉。
throw
例外をスロー。
finally
必ず実行されるブロック。
例外処理
// try-catchtry { 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(自動クローズ)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 ブロックで処理してください。