2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Java 品質を高める例外処理とマルチキャッチ構文まとめ

Posted at

IOException: 入出力操作でエラーが発生した場合にスロー
FileNotFoundException: 指定されたファイルが見つからないときにスロー
SQLException: データベース操作中にエラーが発生した場合にスロー
NumberFormatException: 無効な数値文字列を数値型に変換しようとしたときにスロー
ArithmeticException: 算術演算で不正な操作(例: 0 での除算)をしたときにスロー
ClassCastException: オブジェクトを互換性のない型にキャストしたときにスロー
NullPointerException: null 参照に対してメソッドを呼び出したときにスロー
ReflectiveOperationException: リフレクション操作でエラーが発生したときにスロー

テンプレート 1: ファイル読み込みとマルチキャッチ

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;

public class FileProcessor {
    public void readFile(String filePath) {
        BufferedReader reader = null;
        try {
            reader = new BufferedReader(new FileReader(filePath));
            String line;
            while ((line = reader.readLine()) != null) {
                System.out.println(line);
            }
        } catch (IOException | SecurityException e) {
            System.err.println("ファイル処理中にエラーが発生しました: " + e.getMessage());
        } finally {
            try {
                if (reader != null) {
                    reader.close();
                    System.out.println("リソースが正常に閉じられました");
                }
            } catch (IOException e) {
                System.err.println("リソースのクローズ中にエラーが発生しました: " + e.getMessage());
            }
        }
    }
}

テンプレート 2: データベース接続とマルチキャッチ

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

public class DatabaseHandler {
    public void connectToDatabase() {
        Connection conn = null;
        try {
            conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/mydb", "user", "password");
            System.out.println("データベースに接続しました");
        } catch (SQLException | SecurityException e) {
            System.err.println("データベース接続中にエラーが発生しました: " + e.getMessage());
        } finally {
            try {
                if (conn != null && !conn.isClosed()) {
                    conn.close();
                    System.out.println("データベース接続を閉じました");
                }
            } catch (SQLException e) {
                System.err.println("データベース接続のクローズ中にエラーが発生しました: " + e.getMessage());
            }
        }
    }
}

テンプレート 3: HTTP リクエスト処理とマルチキャッチ


import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

public class HttpRequestHandler {
    public void sendRequest(String urlString) {
        try {
            URL url = new URL(urlString);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("GET");

            int responseCode = conn.getResponseCode();
            System.out.println("HTTP レスポンスコード: " + responseCode);
        } catch (MalformedURLException | IllegalArgumentException e) {
            System.err.println("URL が無効です: " + e.getMessage());
        } catch (IOException e) {
            System.err.println("HTTP リクエストの送信中にエラーが発生しました: " + e.getMessage());
        } finally {
            System.out.println("HTTP リクエスト処理が終了しました");
        }
    }
}

テンプレート 4: JSON パース処理

import org.json.JSONException;
import org.json.JSONObject;

public class JsonParser {
    public void parseJson(String jsonString) {
        try {
            JSONObject jsonObject = new JSONObject(jsonString);
            System.out.println("JSON の解析に成功しました: " + jsonObject.toString(2));
        } catch (JSONException e) {
            System.err.println("JSON パースエラー: " + e.getMessage());
        } finally {
            System.out.println("JSON 処理が完了しました");
        }
    }
}

テンプレート 5: ファイル書き込みとマルチキャッチ


import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;

public class FileWriterHandler {
    public void writeFile(String filePath, String content) {
        try (BufferedWriter writer = new BufferedWriter(new FileWriter(filePath))) {
            writer.write(content);
            System.out.println("ファイルに書き込みました");
        } catch (IOException | SecurityException e) {
            System.err.println("ファイル書き込み中にエラーが発生しました: " + e.getMessage());
        } finally {
            System.out.println("ファイル書き込み処理が完了しました");
        }
    }
}

テンプレート 6: ユーザー入力の検証

import java.util.Scanner;

public class InputValidator {
    public void validateUserInput() {
        Scanner scanner = new Scanner(System.in);
        try {
            System.out.print("整数を入力してください: ");
            int number = Integer.parseInt(scanner.nextLine());
            System.out.println("入力された数値: " + number);
        } catch (NumberFormatException | IllegalStateException e) {
            System.err.println("無効な入力です: " + e.getMessage());
        } finally {
            scanner.close();
            System.out.println("入力処理が完了しました");
        }
    }
}

テンプレート 7: API レスポンスの処理

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

public class ApiHandler {
    public void getApiResponse(String endpoint) {
        try {
            URL url = new URL(endpoint);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("GET");

            try (BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()))) {
                String inputLine;
                StringBuilder response = new StringBuilder();
                while ((inputLine = in.readLine()) != null) {
                    response.append(inputLine);
                }
                System.out.println("API レスポンス: " + response.toString());
            }
        } catch (IOException | SecurityException e) {
            System.err.println("API 呼び出し中にエラーが発生しました: " + e.getMessage());
        } finally {
            System.out.println("API 呼び出し処理が完了しました");
        }
    }
}

テンプレート 8: リフレクションと例外処理

import java.lang.reflect.Method;

public class ReflectionHandler {
    public void invokeMethod(String className, String methodName) {
        try {
            Class<?> clazz = Class.forName(className);
            Method method = clazz.getMethod(methodName);
            method.invoke(clazz.getDeclaredConstructor().newInstance());
            System.out.println("メソッドの呼び出しが成功しました");
        } catch (ClassNotFoundException | NoSuchMethodException e) {
            System.err.println("クラスまたはメソッドが見つかりません: " + e.getMessage());
        } catch (ReflectiveOperationException e) {
            System.err.println("リフレクション中にエラーが発生しました: " + e.getMessage());
        } finally {
            System.out.println("リフレクション処理が完了しました");
        }
    }
}

【参考】

2
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?