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?

More than 3 years have passed since last update.

【Java】例外処理の練習【Exception】

Last updated at Posted at 2020-09-20

対象

初学者向けです。
「例外処理って何?」というレベルの内容です。

整数をゼロで割ってエラーを発生させてみる

Main.java
public class Main {

	public static void main(String[] args) {
		int a = 5;
		int b = 0;
		System.out.println(div(a,b)); // ここでエラーが発生	 
        System.out.println("終了します");
	}

	static int div(int a, int b) {
		return a / b;
	}

}

コンパイルエラーは発生せず、コンパイルできます。
そして実行。

実行結果
Exception in thread "main" java.lang.ArithmeticException: / by zero
	at Main.div(Main.java:19)
	at Main.main(Main.java:9)

エラーが発生している行で処理が終わる

System.out.println(div(a,b));

という部分で

java.lang.ArithmeticException: / by zero

このエラーの後に

System.out.println("終了します");

という処理があるにもかかわらず一行上のエラーが発生している部分で処理が終わっています。

プログラムが強制終了していることになるので、**「エラーが発生したらこうしてね」**という処理を書く必要があります。これが例外処理。

例外ってなに?

エラーのことです。単純にエラーだと考えて差し支えないと思います。厳密には、というか人によって捉え方が違ってくるものらしいので、とりあえず例外処理はエラー処理だと考えておけば大丈夫。

例外処理の書き方try~catch

Main.java

	public static void main(String[] args) {
		int a = 5;
		int b = 0;
		try {
			System.out.println(div(a,b));
		} catch(Exception e) { // エラーをeというオブジェクトで受け取る(オブジェクト名はなんでも良い)
			System.out.println("0で割っています!");
			System.out.println(e); // eを出力
		} finally {
			System.out.println("終了します");
		}
	}

// エラーが発生しそうな計算。エラーがある場合はExceptionクラスにエラー情報を渡す。
	static int div(int a, int b) throws Exception {
		return a / b;
	}

}
try{
エラーが予測される処理
} catch (Exception e) {
エラーが発生した場合の処理
} finally {
エラーが発生してもしなくてもする処理
}

エラーが予測される処理を書く場合に、そこで終了させず、エラーが発生したらcatchの部分エラーが発生した場合の処理をする。これで処理が止まることなく最後まで動いてくれるというもの。

実際実行してみると

0で割っています! // エラーが発生した場合の処理
java.lang.ArithmeticException: / by zero // エラーメッセージ
終了します // finallyまで実行されている
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?