2010-01-30 652 views
1

我有以下簡單的代碼:未報告的異常java.lang.ClassNotFoundException;必須捕獲或聲明拋出

package test; 

import javax.swing.*; 

class KeyEventDemo { 
    static void main(String[] args) { 
    UIManager.setLookAndFeel("javax.swing.plaf.metal.MetalLookAndFeel"); 
    } 
} 

它產生以下錯誤消息:

KeyEventDemo.java:7: unreported exception java.lang.ClassNotFoundException; must be caught or declared to be thrown 
    UIManager.setLookAndFeel("javax.swing.plaf.metal.MetalLookAndFeel"); 
          ^
1 error 

有誰知道什麼是錯的?

回答

9

實際上,該消息是自我解釋:UIManager.setLookAndFeel拋出一堆檢查例外因而需要捕獲(用try/catch塊)或宣佈被拋出(在調用方法中)。

因此,無論周圍的通話用一個try/catch:

public class KeyEventDemo { 
    public static void main(String[] args) { 
     try { 
      UIManager.setLookAndFeel("javax.swing.plaf.metal.MetalLookAndFeel"); 
     } catch (ClassNotFoundException e) { 
      // TODO handle me 
     } catch (InstantiationException e) { 
      // TODO handle me 
     } catch (IllegalAccessException e) { 
      // TODO handle me 
     } catch (UnsupportedLookAndFeelException e) { 
      // TODO handle me 
     } 
    } 
} 

或者添加拋出聲明:

public class KeyEventDemo { 
    public static void main(String[] args) throws ClassNotFoundException, 
     InstantiationException, IllegalAccessException, 
     UnsupportedLookAndFeelException { 
     UIManager.setLookAndFeel("javax.swing.plaf.metal.MetalLookAndFeel"); 
    } 
} 

如果你不想來處理他們每個人以特定的方式

public class KeyEventDemo { 
    static void main(String[] args) { 
     try { 
      UIManager.setLookAndFeel("javax.swing.plaf.metal.MetalLookAndFeel"); 
     } catch (Exception e) { 
      // TODO handle me 
     } 
    } 
} 

或用一拋:這可以通過使用Exception超進行更簡潔的聲明(注意,這傳達的信息較少的方法的調用者,但主叫這裏是JVM的,它並沒有真正在這種情況下重要):

class KeyEventDemo { 
    static void main(String[] args) throws Exception { 
     UIManager.setLookAndFeel("javax.swing.plaf.metal.MetalLookAndFeel"); 
    } 
} 
+0

這是我不太清楚這「checked異常「 我有。對我來說,它與Pyhon中的「try ... except ...」構造看起來很相似。所以,Python試圖做一些事情,如果某個命令不「想」執行某些操作,則會生成類型錯誤消息。但在我的情況下,「錯誤信息」是什麼?我的例外應該是什麼? – Roman 2010-01-30 11:26:39

+0

你是否需要聲明確切的異常類型?它是錯誤消息中給出的「ClassNotFoundException」。 – Ash 2010-01-30 11:36:11

3

重新定義你的方法是

public static void main(String[] args) throws Exception { 
相關問題