Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Wrapping exceptions thrown in super/this constructor calls into other exceptions

I want the api of my module to only throw MyPackageSpecificException whenever anything goes wrong and the module unable to perform its task. (The original exception will be given as the cause of the MyPackageSpecificException).

Now, for one constructor I needed an URL as a parameter to locate a resource. I would also like to make an alternative constructor to which a String representation of the URL can be given:

public MyClass(String urlString) throws MalformedURLException{
    this(new URL(urlString));
}

As the URL constructor throws MalformedURLException, I want to wrap it into a MyPackageSpecificException by doing:

public MyClass(String urlString) throws MyPackageSpecificException{
    try{
        this(new URL(urlString));
    } catch (MalformedURLException e){
        throw new MyPackageSpecificException(e);
    }
}

But, the above is not valid, since the super() or this() constructor call must occur on the first line of the constructor.

The same problem applies if the super() or this() constructor throws an exception which I want to wrap into something else.

How should I solve this? Or is what I am trying to do bad practice?

like image 412
Alderath Avatar asked Aug 14 '09 08:08

Alderath


2 Answers

Try the following:

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);
    }
  }
}
like image 81
Nick Holt Avatar answered Nov 15 '22 09:11

Nick Holt


If it fits your code, you can use a static creator method instead:

private MyClass(String urlString) { ... }

public static MyClass createMyClass(String urlString) throws MyPackageSpecificException {
  try {
    new MyClass(urlString);
  catch (Exception e) {
    throw new MyPackageSpecificException(e);
  }
}
like image 38
Zed Avatar answered Nov 15 '22 07:11

Zed