2012-08-26 33 views
15

這是一個跟進問題Why is this exception is not printed? Why it's 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("Its not gonna printed a="+a); 
     } 
     catch(ArithmeticException e) 
     { 
      System.out.println("Print exception"+e); 
     } 
    } 
} 

取而代之的是輸出來自如下:

Its not gonna printed a=Infinity 

會發生什麼?

回答

27

除零除以整數值拋出異常,但不拋出浮點值。這是在JLS #15.17.2定義:

浮點除法的結果是由IEEE 754算法的規則確定:
[...]

  • 司非零有限值的由零導致有符號無窮大。標誌由上述規則決定。

如果更改ad類型int,你會得到一個異常。

7

因爲Divide by zero適用於整數,而不是浮JLS

,你會得到輸出

Its not gonna printed a=Infinity 

,因爲這是計算爲Infinity

而如果你想看到一個異常只是改變

a=44/d; 

這個

a=44/0;