未报告的异常java.lang.ClassNotFoundException;必须被抓住或宣布被抛出 [英] unreported exception java.lang.ClassNotFoundException; must be caught or declared to be thrown

查看:601
本文介绍了未报告的异常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");
    }
} 

这篇关于未报告的异常java.lang.ClassNotFoundException;必须被抓住或宣布被抛出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆