除算の例外を扱う

概要

演算に例外が発生するとその旨を表示する。

class Divide {
    int dividend;
    int divisor;
    int result;

    Divide(int dividend, int divisor) {
        this.dividend = dividend;
        this.divisor = divisor;
        System.out.print("オブジェクトを生成しました ");
    }

    public int execute() {
        result = this.dividend / this.divisor;
        return result;
    }

    public void showInputData() {
        System.out.println("入力内容は" + "[" + this.dividend + "]/[" + this.divisor + "]");
    }

    public String toString() {
        return "計算結果:[" + this.dividend + "]/[" + this.divisor + "]=[" + result + "]";
    }
}

public class ZeroDiv {
    public static void main(String[] args) {
        try {
            Divide test1 = new Divide(9, 3);
            test1.showInputData();
            test1.execute();
            System.out.println(test1);

            Divide test2 = new Divide(10, 0);
            test2.showInputData();
            test2.execute();
            System.out.println(test2);
        } catch (ArithmeticException e) {
            System.out.println("プログラムの途中でエラーが発生しました"+e.getMessage());
        }
    }
}

実行結果

オブジェクトを生成しました 入力内容は[9]/[3]
計算結果:[9]/[3]=[3]
オブジェクトを生成しました 入力内容は[10]/[0]
プログラムの途中でエラーが発生しました/ by zero

四則演算ゲーム

四則演算ゲーム