ptg7068951
260 HOUR 18:Handling Errors in a Program
LISTING 18.5 The Full Text of PageCatalog.java
1: importjava.net.*;
2:
3: public classPageCatalog {
4: public static voidmain(String[] arguments) {
5: HomePage[] catalog = new HomePage[5];
6: try {
7: catalog[0] = new HomePage(“Mark Evanier”,
8: “http://www.newsfromme.com”, “comic books”);
9: catalog[1] = new HomePage(“Todd Smith”,
10: “http://www.sharkbitten.com”, “music”);
11: catalog[2] = new HomePage(“Rogers Cadenhead”,
12: “http://workbench.cadenhead.org”, “programming”);
13: catalog[3] = new HomePage(“Juan Cole”,
14: “http://www.juancole.com”, “politics”);
15: catalog[4] = new HomePage(“Rafe Colburn”,
16: “www.rc3.org”);
17: for (int i = 0; i < catalog.length; i++) {
18: System.out.println(catalog[i].owner+ “: “ +
19: catalog[i].address+ “ — “ +
20: catalog[i].category);
21: }
22: } catch(MalformedURLException e) {
23: System.out.println(“Error: “+ e.getMessage());
24: }
25: }
26: }
When you run the compiled application, the following output is displayed:
Output▼
Error: no protocol: http://www.rc3.org
The PageCatalogapplication creates an array of HomePageobjects and then
displays the contents of the array. Each HomePageobject is created using up
to three arguments:
. The name of the page’s owner
. The address of the page (as a String, not a URL)
. The category of the page
The third argument is optional, and it is not used in Lines 15–16.
The constructor methods of the HomePageclass throw
MalformedURLExceptionerrors when they receive a string that cannot be
converted into a valid URLobject. These exceptions are handled in the
PageCatalogapplication by using a try-catchblock.