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. and http:// www. are valid, but something such as 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 method includes three things, in this order:

  • The type of object or variable that is returned by the method— a URL object in this case. If this is void, no information is returned by the method.
  • The name of the method— getURL.
  • The argument or arguments, if any, that this method takes— only one in this example, a String variable called urlText.

The TRy-catch block deals with any MalformedURLException errors that occur when URL objects are created. If the string variable sent to the method is a valid web address, it will be sent back as a valid URL object. If not, null is returned. Because you were assigning values to six different URL objects in the pageURL array, the getURL() method makes this process easier to do.