Catching Errors as You Set Up URLs

When you set up a URL object, you must make sure that the text used to set up the address is in a valid format. http://java.sun.com and http:// www.samspublishing.com are valid, but something such as http:www.javaworld.com would not be because of the missing // marks.

The getURL() method takes a string of text as an argument. The string is checked to see whether it's a valid web address, and if it is, the method returns that valid address. If it's erroneous, the method sends back a null value. The following is the getURL() method:

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

The first line of this ...

Get SAMS Teach Yourself Programming with Java™ in 24 Hours, FOURTH 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.