Database Reference
In-Depth Information
return "success";
}
}
Notice that the
doWork()
method is declared with
throws Exception
. The
Exception
class is the
mother of all exceptions and represents any of them. Some of her children exceptions are
IOException
when dealing with files or the network,
SQLException
when dealing with databases and
NullPointerException
when your Java code tries to call a method of a nonexistent object. We can have a
separate
catch
block for each kind of exception that we are anticipating. A method can throw multiple
types of exceptions that may occur.
Catching the general
Exception
would be appropriate whenever we are calling an external block of
code (in this case, our call to the
m.doWork()
method) that may throw any number of exceptions. It
would also be appropriate if, no matter what exception we catch, we handle it identically, as in this case.
Print the Exception Message to System Output Stream
Whatever the exception is that we catch, we will print the identity in the catch block using this
command:
System.out.println( x.toString() );
Every object in Java has a
toString()
method, including exception objects and the objects that you
will create. The
toString()
method is inherited from the
Object
object - more on that later. The
toString()
method returns a
String
type, which can be used to provide the identity or some details
about the object—in the case of exceptions, it provides the exception name.
System.out.println()
sends text to the command prompt window, ending with a line ending
character. Line ending characters differ from one kind of computer to another, for instance, from
Windows to UNIX. Lines end with a carriage return character or line feed character or both.
These terms come from the days of typewriters where the paper rolled around a platen in a carriage
and the carriage moved from right to left as you typed. At the end of each line, the typist would swing a
lever that rolled the platen to feed a line, and push the lever to the left, which would return the carriage
to the start.
Appending a line ending character to a string means the next character will appear underneath the
first character on the current line, i.e., on the next line.
STACKED CALLS
Note that we call
x.toString()
in the
catch
block and pass the returned
String
immediately as a
parameter to
System.out.println()
. We don't create a
String
member variable to hold the value before
printing it. For lack of a better name, I'm going to call this a
stacked call
. See if you can find two very
similar examples of such a call in the code in the next section, Listing 3-5,
ExceptionDemoB.java
. We will
begin to use stacked calls frequently in Chapter 6.
Clean Up as part of Exception Handling
There is a problem with the code of
ExceptionDemoA.java
in Listing 3-4. (The code is repeated in the
following). There are things that get done in the
doWork()
method that need to get undone there as well.