unreported exception java.lang.ClassNotFoundException; must be caught or declared to be thrown
I have the following simple code:
package test;
import javax.swing.*;
class KeyE开发者_Go百科ventDemo {
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?
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).
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
}
}
}
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
}
}
}
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");
}
}
Redefine your method to be
public static void main(String[] args) throws Exception {
精彩评论