x/y运行时错误 [英] x/y a runtime error

查看:53
本文介绍了x/y运行时错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用c#4.0
我有一个问题:


I am using c# 4.0
I have an issue:


int x=10;
int y =0;
int z=x/y;  //<-- this gives an error at runtime..



但是,



however,

int z=10/0;  //<-- this gives an error at compile-time....




我可以知道为什么会这样吗?

谢谢&问候,




May I know why this is the case?

Thanks & Regards,

推荐答案



x和y变量设置在运行时的值.在10/0中,两者都是常量,它们的值在编译时设置.
Hi,

Value in x and y variable setting at run time. Where in 10/0 both are constant, their value setting at compile time.


其他答案的旁注:
这取决于解析器查找"和进行预处理的距离.例如,如果您将使用Delphi,则两者都会给您一个编译时错误,因为它会进行一些严重的预处理.

祝你好运!
Side note to the other answers:
This is dependent how far the parser is "looking" and preprocessing ahead. If you would use Delphi for example, both would have given you a compile time error because it does some serious preprocessing.

Good luck!


Manfred正确答案的注释:

运行时行为不是有充分的理由推断的:在一般情况下,这是不可能的.这是可计算性基本定理之一的结果.如果在一般情况下无法基于静态分析,为什么还要检测某些情况?只是在开发人员中造成错误的安全假象(从而引发错误)?

因此,没有做任何尝试静态分析代码来发现此类问题的尝试-这非常好.

对于像8/2这样的表达式,整个表达式被视为一个单独的immediate constant,在运行时进行评估,并将字节码作为一个常量而不是表达式放入.自然地,将整数除以零会失败. :-)

注意:请注意,将浮点数零除是相当合法的,并且会产生Inf的有效值.您可以继续使用结果;例如1/Inf将被评估为0.

—SA
A note to the correct answer by Manfred:

Run-time behavior is not inferred by a good reason: in general case this is impossible. This is the consequence of one of fundamental theorems of computability. If it is not possible based on static analysis in general case, why detecting some cases? Just to create false illusion of safety in developers (and thus provoking errors)?

By that reason, no attempt to statically analyze code to find such problem is done — and this is very good.

As to the expressions like 8/2, the whole expression is treated as one single immediate constant, evaluated during run-time and put in the byte code as one constant, not as expression. Naturally, integer division by zero fails. :-)

A note: pay attention that division by floating-point zero is quite legal and produce valid value of Inf. You can continue using the result; for example, 1/Inf will be evaluated as 0.

—SA


这篇关于x/y运行时错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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