为什么转换Double.NaN到int不会在Java中抛出异常? [英] Why does casting Double.NaN to int not throw an exception in Java?

查看:517
本文介绍了为什么转换Double.NaN到int不会在Java中抛出异常?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我知道IEEE 754为不是实数的值指定了一些特殊的浮点值。在Java中,将这些值转换为原始 int 不会抛出异常,像我所料想的。相反,我们有以下:

So I know the IEEE 754 specifies some special floating point values for values that are not real numbers. In Java, casting those values to a primitive int does not throw an exception like I would have expected. Instead we have the following:

int n;
n = (int)Double.NaN; // n == 0
n = (int)Double.POSITIVE_INFINITY; // n == Integer.MAX_VALUE
n = (int)Double.NEGATIVE_INFINITY; // n == Integer.MIN_VALUE

在这些情况下抛出异常?这是一个IEEE标准,还是仅仅是Java的设计者的选择?有没有不好的后果,我不知道如果例外是可能的这样的转换?

What is the rationale for not throwing exceptions in these cases? Is this an IEEE standard, or was it merely a choice by the designers of Java? Are there bad consequences that I am unaware of if exceptions would be possible with such casts?

推荐答案


在这些情况下不抛出异常的理由是什么?

What is the rationale for not throwing exceptions in these cases?

我想象的原因包括:


    <

这种行为不是完全意想不到的。

The behaviour is not "totally unexpected".

当应用程序从双精度转换为整数时,预计信息会大量丢失。该应用程序要么忽略这种可能性,要么会在转换前加上检查以防止它...也可以检查这些情况。

When an application casts from a double to an int, significant loss of information is expected. The application is either going to ignore this possibility, or the cast will be preceded by checks to guard against it ... which could also check for these cases.


这是一个IEEE标准,还是仅仅是Java设计人员的选择?

Is this an IEEE standard, or was it merely a choice by the designers of Java?

我认为后者。


有没有不好的后果,我不知道如果例外是可能的这样的施法?

Are there bad consequences that I am unaware of if exceptions would be possible with such casts?

除了明显的例外。 。

(但它并不真正相关JLS和JVM规范说他们说什么,改变它们会破坏现有的代码,它不只是我们现在讨论的Java代码...)

(But it is not really relevant. The JLS and JVM spec say what they say, and changing them would be liable to break existing code. And it is not just Java code we are talking about now ...)

我做了一些挖掘。许多x86指令可以使用从双转换为整数似乎生成硬件中断...除非屏蔽。不清楚(对我来说)指定的Java行为是否比OP建议的替代更容易或更难实现。

I've done a bit of digging. A lot of the x86 instructions that could be used convert from double to integers seem to generate hardware interrupts ... unless masked. It is not clear (to me) whether the specified Java behaviour is easier or harder to implement than the alternative suggested by the OP.

这篇关于为什么转换Double.NaN到int不会在Java中抛出异常?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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