views:

468

answers:

2

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?

+1  A: 

Redefine your method to be

public static void main(String[] args) throws Exception {
skaffman
+4  A: 

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");
    }
} 
Pascal Thivent
It is not clear to me which "checked exception" I have. To me it looks similar to "try... except..." construction in Pyhon. So, Python tries to do something and if a command does not "want" to do something it generates a type error message. But what is the "error message" in my case? What should be my Exception?
Roman
Do you mean the exact exception type you need to declare? It's "ClassNotFoundException", as given in the error message.
Ash