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?
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);
}
}
}
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);
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With