簡體   English   中英

為什么會發生運行時錯誤而不是編譯錯誤?

[英]Why did a run-time error occur instead of a compile error?

我的問題在下面代碼的注釋中:

 static void Main(string[] args)
    {
        int a = int.Parse(Console.ReadLine());
        int div1 = 5/a;  // a isn't Unknown until Runtime, 
                         // if a==0, Runtime error occurred. it's Ok!

        a = 0;
        int div2 = 10/a; // local variable a's Value is zero 
                         // and not exist any sentence 
                         // between "a=0;" and "int div2=10/a;" to change variable a, 
                         // why did a runtime error occur instead of a compile error?
    }

預先感謝您的回答。 我為糟糕的英語寫作道歉,因為英語是我的第二語言。

因為僅在運行時變量a將被分配值0 ,因此除法將失敗並出現DivideByZero異常。

嘗試這樣做int div2 = 10 / 0; 並且會看到編譯器當場拋出一個紅色波浪形錯誤。

如果您將int a聲明int a如下constant情況也是相同的

constant int a = 0;
int div2 = 10 / a;

那是因為,在編譯時; 編譯器將在任何被引用的地方替換常量值,這與直接將其除以0 所以下面的行

int div2 = 10 / a;

會變成

int div2 = 10 / 0; 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM