未报告的异常java.lang.ClassNotFoundException;必须被抓住或宣布被抛出
我有以下简单的代码:
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?
实际上,消息是自我解释: UIManager.setLookAndFeel
抛出一束的检查异常,因此需要被捕获(使用try / catch块)或声明被抛出(在调用方法中)。
Actually, the message is self explaining: UIManager.setLookAndFeel
throws a bunch of checked exceptions that thus need to be caught (with a try/catch block) or declared to be thrown (in the calling method).
所以或者用try / catch来包围电话:
So either surround the call with a 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
}
}
}
或添加一个throws声明:
Or add a throws declaration:
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 Exception
supertype:
public class KeyEventDemo {
static void main(String[] args) {
try {
UIManager.setLookAndFeel("javax.swing.plaf.metal.MetalLookAndFeel");
} catch (Exception e) {
// TODO handle me
}
}
}
或者使用throws声明(注意,这种方式传递给调用者更少的信息,但调用者是这里的JVM,在这种情况下并不重要) :
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):
class KeyEventDemo {
static void main(String[] args) throws Exception {
UIManager.setLookAndFeel("javax.swing.plaf.metal.MetalLookAndFeel");
}
}