Easy to Learn Java: Programming Articles, Examples and Tips

Start with Java in a few days with Java Lessons or Lectures

Home

Code Examples

Java Tools

More Java Tools!

Java Forum

All Java Tips

Books

Submit News
Search the site here...
Search...
 
Search the JavaFAQ.nu
1000 Java Tips ebook

1000 Java Tips - Click here for the high resolution copy!1000 Java Tips - Click here for the high resolution copy!

Java Screensaver, take it here

Free "1000 Java Tips" eBook is here! It is huge collection of big and small Java programming articles and tips. Please take your copy here.

Take your copy of free "Java Technology Screensaver"!.

Java Lesson 42: Claiming and throwing exceptions

JavaFAQ Home » Java Lessons by Jon Huhtala Go to all tips in Java Lessons by Jon Huhtala


Bookmark and Share
All Java Lessons contents page | Java Lesson 1 | Java Lesson 2 | Java Lesson 3 | Java Lesson 4 | Java Lesson 5 | Java Lesson 6 | Java Lesson 7 | Java Lesson 8 | Java Lesson 9 | Java Lesson 10 | Java Lesson 11 | Java Lesson 12 | Java Lesson 13 | Java Lesson 14 | Java Lesson 15 | Java Lesson 16 | Java Lesson 17 | Java Lesson 18 | Java Lesson 19 | Java Lesson 20 | Java Lesson 21 | Java Lesson 22 | Java Lesson 23 | Java Lesson 24 | Java Lesson 25 | Java Lesson 26 | Java Lesson 27 | Java Lesson 28 | Java Lesson 29 | Java Lesson 30 | Java Lesson 31 | Java Lesson 32 | Java Lesson 33 | Java Lesson 34 | Java Lesson 35 | Java Lesson 36 | Java Lesson 37 | Java Lesson 38 | Java Lesson 39 | Java Lesson 40 | Java Lesson 41 | Java Lesson 42 | Java Lesson 43 | Java Lesson 44 | Java Lesson 45 | Java Lesson 46

Java Lesson 42 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

  • Places restrictions on the caller. To call a method that claims a "checked" exception, the call must either be placed within a try block or the calling method must claim the possibility of throwing the uncaught 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

  • Is used to throw an exception object. For example,

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.

  • May not be used to throw a "checked" exception if the method does not claim the exception (or an ancestor). For example,

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

  • Requires special attention because the compiler imposes restrictions on claimed exceptions. For example, assume that a method named doSomething() has the header

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.

  • Is certain to appear on the Java certification exam.

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

  1. 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");
}

  1. the method will not compile because it fails to claim the possibility of throwing a SecurityException

  2. the method will not compile because the throw statement is coded incorrectly

  3. a calling method must either enclose calls to aMethod() in a try block or claim the possibility of throwing a SecurityException

  4. none of the above

  1. 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)

  1. public void aMethod() throws MalformedURLException {
    throw new IOException("We have a problem");
    }

  2. public void aMethod() throws Exception {
    throw new IOException("We have a problem");
    }

  3. public void aMethod() {
    throw new IOException("We have a problem");
    }

  4. public void aMethod() throws IOException {
    throw new MalformedURLException("We have a problem");
    }

  5. public void aMethod() throws MalformedURLException, IOException {
    throw new IOException("We have a problem");
    }

  1. 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

  1. public Emp getEmp(DataInputStream x) throws EOFException

  2. public Emp getEmp(DataInputStream x)

  3. public Emp getEmp(DataInputStream x) throws FileNotFoundException

  4. public Emp getEmp(DataInputStream x) throws Exception

  5. public Emp getEmp(DataInputStream x) throws RuntimeException

  1. 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()");
}
}
  1. a compile error will occur at line 11

  2. a compile error will occur at line 15

  3. Error in x()

  4. Error in y()

  5. the program is terminated with nothing being displayed


 Printer Friendly Page  Printer Friendly Page
 Send to a Friend  Send to a Friend

.. Bookmark and Share

Search here again if you need more info!
Custom Search



Home Code Examples Java Forum All Java Tips Books Submit News, Code... Search... Offshore Software Tech Doodling

RSS feed Java FAQ RSS feed Java FAQ News     

    RSS feed Java Forums RSS feed Java Forums

All logos and trademarks in this site are property of their respective owner. The comments are property of their posters, all the rest 1999-2006 by Java FAQs Daily Tips.

Interactive software released under GNU GPL, Code Credits, Privacy Policy