2013年9月9日 星期一

JAVA-方法丟出例外

Java程式是使用throw指令來自行丟出例外。

public class ch10_2_2 {

    public static void main(String[] args) {
        // TODO 自動產生的方法 Stub
        int result;
        try {
            int a = (int) (Math.random() * 10);
            int b = (int) (Math.random() * 10);
            int c = (int) (Math.random() * 10);
            result = cal(a, b, c);
            System.out.println("計算結果為: " + result);
        } catch (IllegalArgumentException e) {
            // TODO 自動產生的 catch 區塊
            System.out.println("例外說明: "+e.getMessage());
            System.out.println("例外原因: ");
            e.printStackTrace();
        } catch (ArrayIndexOutOfBoundsException e) {
            // TODO 自動產生的 catch 區塊
            System.out.println("例外說明: "+e.getMessage());
            System.out.println("例外原因: ");
            e.printStackTrace();
        }
    }

    static int cal(int a, int b, int c) throws IllegalArgumentException, ArrayIndexOutOfBoundsException{
        int index;
        int[] data = { 22, 14, 36, 68, 87 };
        if (c <= 0) {
            throw new IllegalArgumentException("C小於等於0。");
        } else {
            index = a * b / c;
            if (index >= 5) {
                throw new ArrayIndexOutOfBoundsException("索引值大於5。");
            }
        }
        return data[index];
    }
}

沒有留言:

張貼留言