I have an object “LinkFinder” that I’m having throw an exception if it gets a malformed URL, but I don’t like the idea of using System.out and just printing an error. Instead of the constructor returning the initialized object, can I force it to return null or something?
private URL url;
//constructor in question
public LinkFinder(String sourcePage)
{
try
{
this.url = new URL(sourcePage);
}
catch (MalformedURLException e)
{
System.out.print("Malformed URL Exception: Setting URL to NULL");
this.url = null;
}
}
No you can’t. The only way your constructor will not return an object (or return null) is if it is not completed.
If you want a null object if the
URLis malformed, then the solution would be to apply a try block around your object instantiation code (i.e.new LinkFinder(url)), and in its catch block set the reference to null.