java - 为什么这里被零除不触发异常?

标签 java exception

(这是 Why is this exception is not printed? Why is it showing an error? 的后续问题)

在下面的代码中,为什么没有触发 ArithmeticException?

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 中定义的:

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

  • Division of a nonzero finite value by a zero results in a signed infinity. The sign is determined by the rule stated above.

如果将ad 的类型更改为int,则会出现异常。

关于java - 为什么这里被零除不触发异常?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12130800/

相关文章:

java - 动态注入(inject)属性到spring

java - 获取索引图像的数据(调色板索引)

Java SSL 握手问题

java - Spring Boot从2.1.9升级到2.2后出现InaccessibleObjectException

C++ 异常和 .eh_frame ELF 部分

java - 在spring xml中定义Camel路由有什么优缺点?

java - Java 中抛出异常的高级概述

java - Java 中的通用异常为只读

java - 线程 "main"java.lang.UnsupportedClassVersionError : a (Unsupported major. 次要版本 51.0 中的异常)

java - 外部文件中的嵌套/内部类