为什么整数数据类型以静默方式溢出而不是抛出异常 [英] Why do integer datatypes overflow silently rather than throwing exception

查看:107
本文介绍了为什么整数数据类型以静默方式溢出而不是抛出异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经学会了(至少在java中)整数/长值静默溢出,它们的值从溢出时的最小值开始而不是抛出任何异常。

I have learnt(atleast in java) that integer/long values overflow silently and their values start over from minimum value on overflow rather than throwing any exception.

I正在使用外部api进行某些文件操作,其中从属性文件加载了最大文件大小。在我当地的测试环境中一切都很好。代码进入实时环境后,最大文件大小限制根本不起作用。经过两天的调试/分析代码后,根本没有成功。然后由于其他原因,我采用了live constants.properties文件并用它调试了代码。 o_0

I was using an external api for some file operations, in which max file size was being loaded from a property file. All was fine in my local testing environment. As soon as the code went to live environment, the max file size limit was not working at all. After two days of debugging/analyzing the code, there was no success at all. Then for some other reasons, I took the live constants.properties file and debugged the code with that. o_0

我只想问,是什么阻止他们在溢出时抛出异常?

I just want to ask, what prevented them to throw exception on overflow?

推荐答案

在许多情况下,Java基于C或C ++,它们基于Assembly。溢出/下溢在C和C ++中是静默的,在汇编时几乎是静默的(除非您检查特殊标志)。这可能是因为C和C ++在首次提出时没有例外。如果你想看到溢出/下溢,你只使用了更大的类型。例如 long long int long double ;)BTW程序集与类似于陷阱或中断的异常类似,溢出/下溢不存在引起陷阱AFAIK。

In many cases Java is based on C or C++ and these are based on Assembly. An overflow/underflow is silent in C and C++ and almost silent in assembly (unless you check special flags). This is likely due to the fact that C and C++ didn't have exceptions when they were first proposed. If you wanted to see overflows/underflows you just used a larger type. e.g. long long int or long double ;) BTW assembly has something similar to exceptions called traps or interrupts, overflows/underflow doesn't cause a trap AFAIK.

我更喜欢做的是使用 long double 除非我确定这些类型比需要的大得多。您的设备不能超出 long 大小。

What I prefer to do is use long and double unless I am sure these types are much larger than needed. You can't have a device which overflows long in size.

这篇关于为什么整数数据类型以静默方式溢出而不是抛出异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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