Java:从超级构造函数中捕获异常 [英] Java: Catch exception from super constructor

查看:93
本文介绍了Java:从超级构造函数中捕获异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试编写自己的loader-class来加载加密的类。

I try to write my own loader-class which loads an encryted class.

因此,我也重写了构造方法 loader(ClassLoader paramClassLoader,File paramFile),该调用称为超级(新URL [] {paramFile.toURI()。toURL()},paramClassLoader);

Therefore I also override the contruction loader(ClassLoader paramClassLoader, File paramFile), which calls super(new URL[] { paramFile.toURI().toURL() }, paramClassLoader);.

调用 .toUrl()可能引发 MalformedURLException ,因此编译以下代码...

The call ".toUrl()" can throw an MalformedURLException, so compiling the following code ...

public class loader extends URLClassLoader {
    public static void main(String[] args)throws Exception{
        Object localObject = 
            new loader(loader.class.getClassLoader(), 
                          new File(loader.class.getProtectionDomain().getCodeSource()
                              .getLocation().getPath())
                );
         (...)
    }

    private loader(ClassLoader paramClassLoader, File paramFile){   
        super(new URL[] { paramFile.toURI().toURL() }, paramClassLoader);

        if (paramClassLoader == null)
            throw new IllegalArgumentException("Error loading class");
    }
}

错误:

loader.java:123: error: unreported exception MalformedURLException; must be caught or declared to be thrown
super(new URL[] { paramFile.toURI().toURL() }, paramClassLoader);

如何捕获此异常?
不可能进行try-catch-block,因为对super的调用必须是构造函数中的第一条语句。

How can I catch this exception? A try-catch-block is not possible because the "call to super must be first statement in constructor".

推荐答案

只需向加载器构造函数添加MalformedURLException异常,并使用try catch块将代码包装在main方法中。

Just add throws MalformedURLException to loader constructor and wrap code in main method with try catch block.

public class loader extends URLClassLoader {

    public static void main(String[] args) throws Exception {
        try {
            Object localObject = new loader(loader.class.getClassLoader(),
                    new File(loader.class.getProtectionDomain().getCodeSource()
                            .getLocation().getPath()));
        } catch (MalformedURLException e) {
            // ..
        }
    }

    private loader(ClassLoader paramClassLoader, File paramFile)
            throws MalformedURLException {
        super(new URL[] { paramFile.toURI().toURL() }, paramClassLoader);

        if (paramClassLoader == null) {
            throw new IllegalArgumentException("Error loading class");
        }
    }
}

这篇关于Java:从超级构造函数中捕获异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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