' P '

whatever I will forget

Java 例外処理

Javaもtryとcatchで例外処理を行える。
ひとつ、複数処理したい場合のthrowが少しC++とは違う気がするのでメモ。
* div関数の中にthrowsで例外処理名を定義する * 定義した例外処理はthrow newが必要

public class Program {

    static int div(int a, int b) throws ArithmeticException {
        if(b == 0) {
            throw new ArithmeticException("Division by Zero");
        } else {
            return a / b;
        }
    }

    public static void main(String[] args) {
        System.out.println(div(42, 0));
    }

}