2010-08-05 36 views
0

這是爲什麼就不行,任何一個可以給這一個....我們可以指定一個異常類對象Object類對象的引用

public class Manager 
{ 
    public static void main(String args[]) 
    { 
     try{ 

       Object obj=new A(); //it will generate ClassNotFoundException object 
       System.out.println("currently the reference obj is pointer to the object:"+obj); 

      }catch(Object o) 
        { 
         System.out.println(o); 
        } 

     } 

    System.out.println("End of Main"); 
}  
+0

將你的對象包裝在一個Exception中,然後拋出Exception。在Catch子句中,您可以通過Exception找到對象。 – bzlm 2010-08-05 12:59:08

回答

7

這是行不通的確切的答案只是因爲在「catch」語句中聲明的變量必須是異常類型(即Throwable或子類型)。

從Java語言規範的section 14.20

catch子句必須只有一個 參數(其被稱爲 例外參數);申報 類型異常參數必須 是類Throwable或其Throwable的的一個子類 (不只是一個子類型),或 一個編譯時間錯誤occurs.In 特別是,它是一個編譯時間錯誤 如果聲明類型的例外 參數是一個類型變量(§4.4)。 參數變量的範圍是 catch子句的塊。

當然,你可能

catch(Throwable t) 
{ 
    Object o = t; 
    System.out.println(o); 
} 

目前尚不清楚爲什麼你會想,雖然。

0

你對A類的構造函數一無所知......它實際上拋出一個異常嗎? 如果是,那麼其他答案應該可以幫助你。 如果沒有,那麼也許我可能還記得,instanciating一個異常沒有拋出 ...例外

例子:

這是行不通的:

try { 
new Exception(); 
} catch (Exception e) { 
System.out.println("This will never be printed..."); 
} 

但是你可通過添加throw關鍵字獲得預期結果:

try { 
throw new Exception(); 
} catch (Exception e) { 
System.out.println("This will actually be printed..."); 
} 
相關問題