为什么在这里未触发除以零的异常? [英] Why is the exception not triggered for division by zero here?

查看:93
本文介绍了为什么在这里未触发除以零的异常?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是为什么不打印此异常?为什么显示错误?

下面的代码为何未触发ArithmeticException?

Here in the below code why is the ArithmeticException not triggered?

class Exp
{
    public static void main(String args[])
    {
        float d,a=1;
        try
        {
            d=0;
            a=44/d; //no exception triggered here.. why?
            System.out.print("It's not gonna print: a="+a); 
        }
        catch(ArithmeticException e)
        {
            System.out.println("Print exception: "+e);
        }
    }
} 

相反,输出为:

It's not gonna print: a=Infinity

会发生什么?

推荐答案

除法为零整数值的例外,但浮点值的例外。这在 JLS#15.17.2 中定义a>:

A division by zero throws an exception for integer values, but not for floating values. This is defined in the JLS #15.17.2:


浮点除法的结果由IEEE 754算术规则确定:

[...]

The result of a floating-point division is determined by the rules of IEEE 754 arithmetic:
[...]


  • 将非零有限值除以零会导致有符号无穷大。该标志由上述规则确定。

如果更改 a 和 d int ,您将得到一个例外。

If you change the type of a and d to int, you will get an exception.

这篇关于为什么在这里未触发除以零的异常?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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