包装在super/this构造函数中抛出的异常会调用其他异常

Ald*_*ath 6 java constructor exception

我希望我的模块的api只在出现任何错误并且模块无法执行其任务时抛出MyPackageSpecificException.(原始异常将作为MyPackageSpecificException的原因给出).

现在,对于一个构造函数,我需要一个URL作为查找资源的参数.我还想创建一个替代构造函数,可以为其指定URL的String表示形式:

public MyClass(String urlString) throws MalformedURLException{
    this(new URL(urlString));
}
Run Code Online (Sandbox Code Playgroud)

由于URL构造函数抛出MalformedURLException,我想通过执行以下操作将其包装到MyPackageSpecificException中:

public MyClass(String urlString) throws MyPackageSpecificException{
    try{
        this(new URL(urlString));
    } catch (MalformedURLException e){
        throw new MyPackageSpecificException(e);
    }
}
Run Code Online (Sandbox Code Playgroud)

但是,上面的内容无效,因为super()或this()构造函数调用必须出现在构造函数的第一行.

如果super()或this()构造函数抛出我想要包装到其他内容的异常,则同样的问题也适用.

我该怎么解决这个问题?或者我正在努力做坏事?

Nic*_*olt 6

请尝试以下方法:

public class MyClass
{
  private URL url;

  public MyClass(URL url)
  {
    this.url = url;
  }

  public MyClass(String urlString) throws MyPackageSpecificException
  { 
    this(toURL(urlString));
  }

  private static URL toURL(String urlString) throws MyPackageSpecificException
  {
    try
    {
      return new URL(urlString));
    } 
    catch (MalformedURLException e)
    {
        throw new MyPackageSpecificException(e);
    }
  }
}
Run Code Online (Sandbox Code Playgroud)