Throwing and Catching Exceptions

For the next project, you create a class that uses exceptions to tell another class about an error that has taken place.

The classes in this project are HomePage, a class that represents a personal home page on the Web, and PageCatalog, an application that catalogs these pages.

Enter the text of Listing 18.4 in a new empty Java file called HomePage.

Listing 18.4. The Full Text of HomePage.java


 1: import java.net.*;
 2:
 3: public class HomePage {
 4:     String owner;
 5:     URL address;
 6:     String category = "none";
 7:
 8:     public HomePage(String inOwner, String inAddress)
 9:         throws MalformedURLException {
10:
11:         owner = inOwner;
12:         address = new URL(inAddress);
13:     }
14:
15:     public HomePage(String inOwner, String inAddress, String inCategory)
16:         throws MalformedURLException {
17:
18:         this(inOwner, inAddress);
19:         category = inCategory;
20:     }
21: }


You can use the compiled HomePage class in other programs. This class represents personal web pages on the Web. It has three instance variables: address, a URL object representing the address of the page; owner, the person who owns the page; and category, a short comment describing the page’s primary subject matter.

Like any class that creates URL objects, HomePage must either deal with MalformedURLException errors in a try-catch block or declare that it is ignoring these errors.

The class takes the latter course, as shown in Lines 8–9 and Lines 15–16. By using throws in the two constructor methods, HomePage removes the need to deal with MalformedURLException errors in any way.

To create an application that uses the HomePage class, return to NetBeans and create an empty Java file called PageCatalog that contains the text of Listing 18.5.

Listing 18.5. The Full Text of PageCatalog.java


 1: import java.net.*;
 2:
 3: public class PageCatalog {
 4:     public static void main(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: www.rc3.org


The PageCatalog application creates an array of HomePage objects and then displays the contents of the array. Each HomePage object 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 HomePage class throw MalformedURLException errors when they receive a string that cannot be converted into a valid URL object. These exceptions are handled in the PageCatalog application by using a try-catch block.

To correct the problem causing the “no protocol” error, edit Line 16 so the string begins with the text http:// like the other web addresses in Lines 7–14. When you run the program again, you see the output shown in Figure 18.3.

Figure 18.3. The output of the PageCatalog application.

Image

Summary

Now that you have put Java’s exception handling techniques to use, the subject of errors ought to be a bit more popular than it was at the beginning of the hour.

You can do a lot with these techniques:

• Catch an exception and deal with it.

• Ignore an exception, leaving it for another class or the Java interpreter to take care of.

• Catch several different exceptions in the same try-catch block.

• Throw your own exception.

Managing exceptions in your Java programs makes them more reliable, more versatile, and easier to use because you don’t display any cryptic error messages to people who are running your software.

Q&A

Q. Is it possible to create your own exceptions?

A. You can create your own exceptions easily by making them a subclass of an existing exception, such as Exception, the superclass of all exceptions. In a subclass of Exception, there are only two methods you might want to override: Exception() with no arguments and Exception() with a String as an argument. In the latter, the string should be a message describing the error that has occurred.

Q. Why doesn’t this hour cover how to throw and catch errors in addition to exceptions?

A. Java divides problems into Errors and Exceptions because they differ in severity. Exceptions are less severe, so they are something that should be dealt with in your programs using try-catch or throws in the method declaration. Errors, on the other hand, are more serious and can’t be dealt with adequately in a program.

Two examples of these errors are stack overflows and out-of-memory errors. These can cause the Java interpreter to crash, and there’s no way you can fix them in your own program as the interpreter runs it.

Q. What is the oldest comic strip that’s still running in newspapers?

A. Katzenjammer Kids, which was created by Rudolph Dirks in 1897 and is still offered today by King Features Syndicate. The strip was started only two years after the first comic strip, The Yellow Kid, and is the first to use speech balloons.

Dirks, a German immigrant to the United States, was inspired to create the rebellious kids Hans and Fritz by a children’s story from his native country. He quit the strip in 1912 in a contractual dispute and was succeeded by Harold Knerr, who wrote and drew it until 1949. There have been five subsequent cartoonists working on it. Hy Eisman has been doing it since 1986.

The word katzenjammer literally means “the wailing of cats” in German, but it’s more often used to describe a hangover.

Workshop

Although this hour is literally filled with errors, see if you can answer the following questions about them without making any errors of your own.

Quiz

1. How many exceptions can a single catch statement handle?

A. Only one.

B. Several different exceptions.

C. This answer intentionally left blank.

2. When are the statements inside a finally section be run?

A. After a try-catch block has ended with an exception

B. After a try-catch block has ended without an exception

C. Both

3. With all this talk about throwing and catching, what do the Texas Rangers need to do in the off season?

A. Get more starting pitching.

B. Sign a left-handed power-hitting outfielder who can reach the short porch in right.

C. Bring in new middle relievers.

Answers

1. B. An Exception object in the catch statement can handle all exceptions of its own class and its superclasses.

2. C. The statement (or statements) in a finally section always are executed after the rest of a try-catch block, whether an exception has occurred.

3. A. Every answer is correct, but A is more correct than the others and will probably be correct for the next 30 years.

Activities

To see whether you are an exceptional Java programmer, try to make as few errors as possible in the following activities:

• Modify the NumberDivider application so that it throws any exceptions that it catches and run the program to see what happens.

• There’s a try-catch block in the LottoEvent class you created in Hour 15, “Responding to User Input.” Use this block as a guide to create your own Sleep class, which handles InterruptedException so other classes such as LottoEvent don’t need to deal with them.

To see Java programs that implement these activities, visit the book’s website at www.java24hours.com.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.144.7.151