0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

例外についての基礎知識備忘録 feat.2年目エンジニア

Posted at

はじめに

2年目になって初めて本格的にJavaを用いた開発業務に携わることになったのですが、研修以来Javaの学習はおざなりだったので、例外についての知識が結構抜けていました。
そこで例外処理についての基礎知識を本記事に残しておこうと思った次第です。

例外について

例外とは何か

Javaにおける「例外(Exception)」とは、プログラム実行中に発生する異常な状態のことです。
例:ゼロ除算、ファイルが存在しない、nullアクセスなど。

Javaでは、エラーが起きた瞬間に「例外オブジェクト」が生成され、throwで投げられ、catchで受け取って処理します。
Javaの例外処理は「問題が起きた時に、どう対応するか」を明示する仕組みです。

基本構文

try-catch-finally の基本構文
try {
    // 問題が起きそうなコード
} catch (Exception e) {
    // エラーが発生した場合の処理
} finally {
    // 成功しても失敗しても最後に実行(後処理などに使う)
}

throw と throws

throw:実際に例外を投げる

throw 例
throw new IllegalArgumentException("引数が不正です");

throws:メソッドの定義で「例外が起こるかも」と宣言する
throws 例
public void readFile(String path) throws IOException {
    // ファイルを読み込む処理
}

Checked例外 vs Unchecked例外

Checked例外:コンパイル時にcatchまたはthrowsが必須の例外
例:Checked例外 IOException, SQLException コンパイル時にcatchまたはthrowsが必須

Checked例外
try {
    FileReader reader = new FileReader("test.txt");
} catch (IOException e) {
    e.printStackTrace();
}

Unchecked例外:実行時のみ発生する例外、catchは任意(設計ミス系)
例:NullPointerException, IllegalArgumentException

Unchecked例外
String str = null;
System.out.println(str.length()); // NullPointerExceptioncatch不要

独自例外

プロジェクトによっては「自分専用の例外」を作ることもある。

独自例外クラス 例
public class MyAppException extends Exception {
    public MyAppException(String message) {
        super(message);
    }
}
使い方 例
public void validateUser(String name) throws MyAppException {
    if (name == null || name.isEmpty()) {
        throw new MyAppException("ユーザー名が未入力です");
    }
}

参考リンク

Java公式ドキュメント(例外処理)

https://docs.oracle.com/javase/tutorial/essential/exceptions/

#######

0
0
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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?