Javaにおける例外処理とデバッグ技術の実践

例外処理の基本概念

Javaの例外処理メカニズムは、プログラムのエラー発生箇所から適切な処理が可能な位置へ制御を移す仕組みです。主なエラー要因として:

  • ユーザ入力エラー
  • デバイス障害
  • 物理的制限
  • コーディングミス

例外の分類

例外はThrowableクラスを継承し、大きく2種類に分類されます:

// 例外クラス階層の例
try {
  FileInputStream file = new FileInputStream("data.txt");
} catch (FileNotFoundException e) {
  System.out.println("ファイルが見つかりません");
}

実践的な例外処理例

ファイル読み込み処理

public class FileProcessor {
  public static void main(String[] args) {
    try {
      BufferedReader reader = new BufferedReader(
        new FileReader("data.csv"));
      String line;
      while ((line = reader.readLine()) != null) {
        System.out.println(line);
      }
    } catch (IOException e) {
      System.err.println("IOエラーが発生しました: " + e.getMessage());
    }
  }
}

カスタム例外の作成

class InvalidAgeException extends Exception {
  public InvalidAgeException(String message) {
    super(message);
  }
}

public class AgeValidator {
  public void validate(int age) throws InvalidAgeException {
    if (age < 0) {
      throw new InvalidAgeException("年齢が不正です: " + age);
    }
  }
}

デバッグ技術

スタックトレースの活用

public class StackTraceDemo {
  public static void main(String[] args) {
    try {
      recursiveMethod(3);
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
  
  static void recursiveMethod(int depth) {
    if (depth == 0) {
      throw new RuntimeException("基底ケース到達");
    }
    recursiveMethod(depth - 1);
  }
}

Eclipseデバッグ機能

  • 条件付きブレークポイント
  • 変数監視ブレークポイント
  • 例外発生時の自動停止
  • ステップ実行による処理追跡

ログ記録の実装

import java.util.logging.*;

public class LoggingExample {
  private static final Logger logger = Logger.getLogger(LoggingExample.class.getName());
  
  public static void main(String[] args) {
    logger.setLevel(Level.ALL);
    
    try {
      int result = 10 / 0;
    } catch (Exception e) {
      logger.log(Level.SEVERE, "除算エラーが発生", e);
    }
    
    logger.info("プログラム正常終了");
  }
}

四則演算プログラムの例

public class ArithmeticQuiz {
  public static void main(String[] args) {
    Random rand = new Random();
    int score = 0;
    
    for (int i = 1; i <= 10; i++) {
      int a = rand.nextInt(100);
      int b = rand.nextInt(100);
      int op = rand.nextInt(4);
      
      try {
        double answer = calculate(a, b, op);
        // クイズ処理続行
      } catch (ArithmeticException e) {
        System.out.println("計算エラー: " + e.getMessage());
      }
    }
  }
  
  static double calculate(int a, int b, int op) {
    switch(op) {
      case 0: return a + b;
      case 1: return a - b;
      case 2: return a * b;
      case 3: 
        if (b == 0) throw new ArithmeticException("ゼロ除算");
        return (double)a / b;
      default: throw new IllegalArgumentException("無効な演算子");
    }
  }
}

タグ: Java 例外処理 デバッグ ロギング スタックトレース

7月13日 18:12 投稿