我尝试编写我自己的加载类的加载类。Java:从超级构造函数捕获异常
因此,我也覆盖构造loader(ClassLoader paramClassLoader, File paramFile)
,其调用super(new URL[] { paramFile.toURI().toURL() }, paramClassLoader);
。
呼叫 “.toUrl()” 可以抛出MalformedURLException
,所以编译如下代码...
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 super call必须是构造函数中的第一条语句”。
一般来说,你应该避免在构造函数中发生任何类型的异常。为什么不传递paramFile.toURI()。toURL()作为构造函数的参数?通过这种方式,您可以在创建对象之前捕获异常。 –