2015-10-04 128 views
0
import static java.lang.System.*; 
import java.io.*; 

public class ExceptionDemo { 


    public static void main(String args[]) { 
     try { 
       int x = 5/0; 
     }finally { 

      System.out.print("exception "); 
     } 
    } 
} 

import static java.lang.System.*; 
import java.io.*; 

public class ExceptionDemo { 


    public static void main(String args[]) { 
     try { 
      throw new Exception(); 
     } finally { 
      System.out.print("exception "); 
     } 
    } 
} 
+1

第一個沒有明確地拋出任何異常,而第二個沒有,你沒有以任何方式處理它(抓住它或進一步拋出) – Titus

+0

@JeroenVannevel不,它不。有一個未捕獲的例外。 – BackSlash

+0

@BackSlash:沒關係,我沒有注意到Ideone自己自動添加它。 –

回答

0

你有兩個選擇:

要麼捕獲異常你扔:

public static void main(String args[]) { 
    try { 
     throw new Exception(); 
    } catch (Exception e) { 
     e.printStackTrace(); 
    } finally { 
     System.out.print("exception "); 
    } 
} 

要麼讓你方法扔它:

public static void main(String args[]) throws Exception { 
    try { 
     throw new Exception(); 
    } finally { 
     System.out.print("exception "); 
    } 
} 

但是你必須處理它。我自己喜歡捕捉並直接處理它。

+0

謝謝@yassin hajaj –

+0

@piyushjoshi不客氣。不要忘記標記爲接受:)。 –

相關問題