Java除以零不会抛出ArithmeticException - 为什么? [英] Java division by zero doesnt throw an ArithmeticException - why?

查看:220
本文介绍了Java除以零不会抛出ArithmeticException - 为什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么这段代码不会抛出 ArithmeticException ?看一下:

Why this code doesn't throw an ArithmeticException? Take a look:

public class NewClass {

    public static void main(String[] args) {
        // TODO code application logic here
        double tab[] = {1.2, 3.4, 0.0, 5.6};

        try {
            for (int i = 0; i < tab.length; i++) {
                tab[i] = 1.0 / tab[i];
            }
        } catch (ArithmeticException ae) {
            System.out.println("ArithmeticException occured!");
        }
    }
}

我不知道!

推荐答案

为什么你不能自己检查并在你想要的时候抛出异常。

Why can't you just check it yourself and throw an exception if that is what you want.

    try {
        for (int i = 0; i < tab.length; i++) {
            tab[i] = 1.0 / tab[i];

            if (tab[i] == Double.POSITIVE_INFINITY ||
                    tab[i] == Double.NEGATIVE_INFINITY)
                throw new ArithmeticException();
        }
    } catch (ArithmeticException ae) {
        System.out.println("ArithmeticException occured!");
    }

这篇关于Java除以零不会抛出ArithmeticException - 为什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆