未报告的异常 java.lang.ClassNotFoundException; 必须被捕获或声明被抛出
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2167642/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
unreported exception java.lang.ClassNotFoundException; must be caught or declared to be thrown
提问by Roman
I have the following simple code:
我有以下简单的代码:
package test;
import javax.swing.*;
class KeyEventDemo {
static void main(String[] args) {
UIManager.setLookAndFeel("javax.swing.plaf.metal.MetalLookAndFeel");
}
}
It generates the following error message:
它生成以下错误消息:
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
Does anybody know what is wrong?
有人知道出了什么问题吗?
回答by Pascal Thivent
Actually, the message is self explaining: UIManager.setLookAndFeelthrows a bunch of checkedexceptions that thus need to be caught (with a try/catch block) or declared to be thrown (in the calling method).
实际上,该消息是自我解释的:UIManager.setLookAndFeel抛出一堆已检查的异常,因此需要捕获(使用 try/catch 块)或声明要抛出(在调用方法中)。
So either surround the call with a 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
}
}
}
Or add a throws declaration:
或者添加一个 throws 声明:
public class KeyEventDemo {
public static void main(String[] args) throws ClassNotFoundException,
InstantiationException, IllegalAccessException,
UnsupportedLookAndFeelException {
UIManager.setLookAndFeel("javax.swing.plaf.metal.MetalLookAndFeel");
}
}
If you don't want to handle each of them in a specific way, this can be made less verbose by using the Exceptionsupertype:
如果您不想以特定方式处理它们中的每一个,可以通过使用Exception超类型来减少冗长:
public class KeyEventDemo {
static void main(String[] args) {
try {
UIManager.setLookAndFeel("javax.swing.plaf.metal.MetalLookAndFeel");
} catch (Exception e) {
// TODO handle me
}
}
}
Or with a throws declaration (note that this convey less information to the caller of the method but the caller being the JVM here, it doesn't really matter in this case):
或者使用 throws 声明(请注意,这向方法的调用者传达的信息较少,但此处的调用者是 JVM,在这种情况下并不重要):
class KeyEventDemo {
static void main(String[] args) throws Exception {
UIManager.setLookAndFeel("javax.swing.plaf.metal.MetalLookAndFeel");
}
}
回答by skaffman
Redefine your method to be
重新定义你的方法
public static void main(String[] args) throws Exception {

