|
JavaFAQ Home » Java Lessons by Jon Huhtala

Claiming and throwing exceptions
Overview
In the previous lesson, you learned how to use
try, catch, and finally blocks to detect and
recover from exceptions. In this lesson, you will learn how to create an Exception object and throw it.
Before you are allowed to throw an exception, however, you
may need to claim the right to throw it.
The throws keyword
-
Is required in order to throw a "checked"
exception. Exceptions that descend from RuntimeException can be thrown at any time without claiming the
right.
-
Is coded on a method header to "claim" that a
specific type of exception may be thrown by the method. For example,
public int getSomething() throws IOException
specifies that the getSomething() method may throw an IOException or a descendent of
IOException.
If multiple exceptions may be thrown, they can
be individually claimed as show by
public int networkingMethod() throws SocketException,
ProtocolException
which claims that either a SocketException or a ProtocolException (or a
descendent) may be thrown by networkingMethod().
Because descendents of the claimed exception
may be thrown, and the Exception class is the ancestor of all other exception classes,
the following is an example of a method header that claims the possibility
that any kind of exception may be thrown.
public String find(String[] strings) throws Exception
For example, assume method2() claims the possibility of throwing an
EOFException. To call it
from a method named method1(), either of the following will satisfy the compiler:
public void method1() { try { method2(); } catch
(EOFException err) { } }
or
public void method1()
throws
EOFException
{ method2(); }
Note that an ancestor of EOFException could also be caught or claimed (such as Exception).
The throw keyword
throw new
NullPointerException();
will instantiate and throw a NullPointerException object having a default message "null". All exception objects
provide an overloaded constructor that accept an overriding message. For
example,
throw new
NullPointerException("No object exists");
will instantiate and throw a NullPointerException object having the message "No object exists".
To throw a general purpose exception, one might
code
throw new Exception("An
error has occurred");
which instantiates and throws an Exception object having the message "An error has occurred". Note that this is a
checked exception. A caller will be forced to either code a try-catch or claim an Exception.
public void mightFail()
{ throw new IOException(); }
will not compile because IOException is a checked exception and must be claimed. The
following,
public void mightFail()
throws Exception { throw new
IOException(); }
will compile because IOException is a descendent of Exception.
Overriding a method that throws an
exception
public String doSomething(String[] strings) throws
IOException
Overriding it with a method having the
header
public String doSomething(String[] strings) throws
IOException
will compile successfully. But, overriding it
with a method whose header is
public String doSomething(String[] strings) throws
Exception
will result in a compile error. The rule is
that a method that claims an exception can only be overridden by a method that
claims the same exception, a descendent exception, or no exception. For
example, the doSomething() method could also be overridden by a method having
the header:
public String doSomething(String[] strings) throws
EOFException
because EOFException descends from IOException.
The following method header would also be valid
for overriding the doSomething() method:
public String doSomething(String[] strings)
These restrictions ensure that existing try - catch code will continue to process correctly.
Remember that a catch
block can catch
descendent exceptions.
Here is a sample program that will help you
master this material. It is merely a testing tool. The App class extends the SuperApp class and overrides
the inherited doSomething() method to throw a more specific checked exception.
The import statements make it possible to access various input/output and
networking classes within the Java packaged code.
import java.io.*; import java.net.*;
// This is the root
class for the application. It has a method that // throws an
IOException.
class SuperApp { public void doSomething()
throws IOException { throw new IOException("Something
happened..."); } }
// This class extends the superApp
class.
public class App extends SuperApp { public static
void main(String[] args) { App x = new
App(); try {
x.doSomething(); } catch
(Exception err) {
System.out.println(err.getMessage()); }
}
// Override the inherited method to throw a more
specific // SocketException.
public void
doSomething() throws SocketException { throw new
SocketException("Socket error..."); } }
When testing, try changing the exception
types that are claimed and thrown in both the inherited and overridden
methods to see what happens.
Efficiency considerations
Throwing an exception involves more system overhead than simply returning a
value to the caller. For that reason, the unnecessary throwing of exceptions
should be avoided in a well-designed program.
Lab exercise for Ferris
students
E-mail your answers to this
assignment no later than
the due date listed in the class schedule.
Review questions
-
Based on the fact that SecurityException is a subclass of RuntimeException, which one of the statements
below is true of the following method?
public void aMethod() { throw new
SecurityException("Violation"); }
-
the method will not
compile because it fails to claim the possibility of throwing a SecurityException
-
the method will not
compile because the throw statement
is coded incorrectly
-
a calling method must
either enclose calls to aMethod() in
a try block or claim the possibility
of throwing a SecurityException
-
none of the above
-
Based on the fact that IOException is a subclass of Exception and a superclass of MalformedURLException, which of the following
method definitions are properly coded? (choose three)
-
public void aMethod() throws MalformedURLException { throw
new IOException("We have a problem"); }
-
public void aMethod() throws Exception { throw new
IOException("We have a problem"); }
-
public void aMethod() { throw new IOException("We have a
problem"); }
-
public void aMethod() throws IOException { throw new
MalformedURLException("We have a problem"); }
-
public void aMethod() throws MalformedURLException, IOException
{ throw new IOException("We have a problem"); }
-
If a superclass method has
the following header, and based on the fact that IOException is a subclass of Exception and a superclass of FileNotFoundException and EOFException, which of the overriding method headers coded below
are properly coded? (choose two)
public Emp getEmp(DataInputStream x) throws
IOException
-
public Emp getEmp(DataInputStream x) throws EOFException
-
public Emp getEmp(DataInputStream x)
-
public Emp getEmp(DataInputStream x) throws
FileNotFoundException
-
public Emp getEmp(DataInputStream x) throws Exception
-
public Emp getEmp(DataInputStream x) throws RuntimeException
-
What will be displayed when
an attempt is made to compile and execute the following program? The line
numbers are for reference purposes only.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
public
class App { public static void main(String[] args)
{ try {
x(); } catch (Exception
err) {
System.out.println(err.getMessage());
} } public static void x() throws Exception
{ y(); throw new
Exception("Error in x()"); } public static void
y() { throw new RuntimeException("Error in
y()"); } } |
-
a compile error will occur
at line 11
-
a compile error will occur
at line 15
-
Error in x()
-
Error in y()
-
the program is terminated
with nothing being displayed Printer Friendly Page
Send to a Friend
..
Search here again if you need more info!
|