はじめに
今回はJavaの例外処理である「try-catch」「throws・throw」について勉強したことを記載していきたいと思います。
例外の種類
例外には大きく分けて3つの種類が存在します。
| Error | Unchecked例外:例外処理をしなくてもコンパイル可能 回復の見込みがない致命的な例外。メモリ不足やクラスファイルが壊れているなど回復飲み込みがないエラーのため例外処理を記述することはありません。 例)OutOfMemoryError | 
| Exception | checked例外:例外処理をしないとコンパイルエラー 例外を想定して、発生した場合の処理を記述しておくべき例外。ネットワーク障害やDB操作・ファイル操作など、失敗した際の処理を記述しておかないと他に大きな影響を与えてしまう例外です。 例)IOException | 
| Runtime Exception | Unchecked例外:例外処理をしなくてもコンパイル可能 処理実行時に発生する例外で全てを考慮するのは難しいため、必ずしも全てを想定して例外処理をすることはありません。 例)NullPointerException | 
try-catch
例外処理の一つとして「try-catch」の構文が存在します。
| try句 | 例外が発生しそうな処理を記述する | 
| catch句 | 例外が発生した際の処理を記述する | 
| finally句 | 例外が発生してもしなくても必ず実施する処理を記述する | 
構文
try {
 // 例外が発生しそうな処理を記述する
} catch {
 // 例外処理を記述する
} finally {
 // 必ず実行する処理を記述する
}
例
import java.io.FileWriter;
public class App {
    /**
     * @param args
     * @throws Exception
     */
    public static void main(String[] args) throws Exception {
        FileWriter fw = null;
        try {
            fw = new FileWriter("./Test.txt");
            fw.append("書き込み");
            fw.flush();
        } catch (IOException ioe) {
            System.out.println("IOExceptionが発生:" + ioe.getMessage());
        } catch (Exception e) {
            System.out.println(e.getMessage());
        } finally {
            fw.close();
        }
    }
}
throws
「throws」も例外処理の一つとして存在します。メソッドに想定した発生しうる例外を「throws」を使用して記述しておくことで、例外が発生した場合の処理を呼び出し元に任せることができます。
構文
修飾子 戻り値の型 メソッド名 (引数) throws 例外クラス名 {
} 
例
import java.io.FileWriter;
public class App {
    /**
     * @param args
     * @throws Exception
     */
    public static void main(String[] args) throws Exception {
        try {
            writeText("書き込み");
        } catch (IOException ioe) {
            System.out.println("IOExceptionが発生:" + ioe.getMessage());
        } catch (Exception e) {
            System.out.println(e.getMessage());
        } 
    }
    /**
     * テキストファイル書き込み
     * @throws IOException
     * @throws Exception
     */
    public static void writeText(String text) throws IOException, Exception {
        FileWriter fw = null;
        fw = new FileWriter("./Test.txt");
        fw.append(text);
        fw.flush();
        fw.close();
    }
}
throw
「throw」を使用することで、例外を任意に発生させることも可能です。
構文
throw 例外クラスのインスタンス化
例
import java.io.FileWriter;
public class App {
    /**
     * @param args
     * @throws Exception
     */
    public static void main(String[] args) throws Exception {
        try {
            throw new IOException("テストメッセージ");
        } catch (IOException ioe) {
            System.out.println("IOExceptionが発生:" + ioe.getMessage());
        } 
    }
}
独自例外クラス
例外クラスを継承することで、独自の例外クラスを定義し特有の例外クラスを作成することも可能です。
例
package Exception;
public class TestException extends Exception {
    /*
     * コンストラクタ
     */
    public TestException (String message) {
        super(message);
    }
}
import Exception.*;
public class App {
    /**
     * @param args
     * @throws Exception
     */
    public static void main(String[] args) throws Exception {
        try {
            throw new TestException("独自エラーメッセージ");
        } catch (TestException teste) {
            System.out.println("TestExceptionが発生:" + teste.getMessage());
        } 
    }
}
ドキュメント
【公式ドキュメント】
Java SE Specifications (oracle.com)
最後に
Javaの環境構築は、この記事を参照してみてください。
【開発環境構築】VS CodeでJavaを使用するための環境構築を実施する – SEもりのLog (selifemorizo.com)
以上、ログになります。
これからも継続していきましょう!!

 
  
  
  
  

コメント