LoginSignup
2
0

More than 3 years have passed since last update.

【Java】0で割る割り算の例外処理

Last updated at Posted at 2020-11-24

プログラミング勉強日記

2020年11月24日
Javaで電卓のプログラムを組んでいるときに0での割り算でエラーが出てプログラムが強制終了したので、その例外処理の方法を記述する。

異常終了する場合

 Javaでは条件を見たなさにと起こる例外があり、例外処理をしないとプログラムが異常終了することがある。以下のサンプルコードのように例外処理をしないと、異常終了する。

異常終了するサンプルコード
public class Main {
    public static void main(String[] args) {
        int a = 123;
        int b = 0;
        int c;
        c = a / b;
    }
}
実行結果
Exception in thread "main" java.lang.ArithmeticException: / by zero
        at ZeroDividException.main(ZeroDividException.java:7)

 このように0で割ってしまっているのでプログラムが強制終了する。

0での割り算における例外処理

 プログラムの異常終了を防ぐために、例外処理を加える。

public class Main {
    public static void main(String[] args) {
        try{
            int a = 123;
            int b = 0;
            int c;
            c = a / b;
         } catch(ArithmeticException e) {
                 System.out.println("エラー(0で割っています)"); 
         }
     }
}
実行結果
エラー(0で割っています)

 例外処理をすっることで、エラーメッセージを表示させて強制終了を防ぐことができる。

参考文献

例外処理
Java(例外処理)

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