Catching Errors as You Set Up URLs

When you set up a URL object, you must make sure the text used to set up the address is in a valid format. http://workbench.cadenhead.org and http://www.samspublishing.com are valid, but http:www.javaworld.com would not be because of missing “/” marks.

The getURL(String) method takes a web address as an argument, returning a URL object representing that address. If the string is not a valid address, the method returns null instead:

URL getURL(String urlText) {    URL pageURL = null;    try {        pageURL = new URL(getDocumentBase(), urlText);    } catch (MalformedURLException m) {        // do nothing    }    return pageURL;}

The try-catch block deals with any MalformedURLException errors that occur when ...

Get Sams Teach Yourself Java™ in 24 Hours, Sixth Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.