我有以下简单的代码:
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
有人知道出了什么问题吗?
答案 0 :(得分: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");
}
}
如果您不想以特定方式处理每一个,可以使用Exception
超类型来减少这一点:
public class KeyEventDemo {
static void main(String[] args) {
try {
UIManager.setLookAndFeel("javax.swing.plaf.metal.MetalLookAndFeel");
} catch (Exception e) {
// TODO handle me
}
}
}
或者使用throws声明(请注意,这会向方法的调用者传递较少的信息,但调用者是JVM,这在这种情况下并不重要):
class KeyEventDemo {
static void main(String[] args) throws Exception {
UIManager.setLookAndFeel("javax.swing.plaf.metal.MetalLookAndFeel");
}
}
答案 1 :(得分:3)
重新定义您的方法
public static void main(String[] args) throws Exception {