您的位置:寻梦网首页编程乐园Java天地Core JavaJava Lecture Notes

Introduction

Content

Apply

Reflect

Extend

previous.gif
 (3087 bytes)

next.gif
 (2959 bytes)

 

Content Index

Content Page # 39

Passing an exception upwards

Suppose we are writing a method that does some file manipulations, but it is not appropriate for the exceptions to be handled in that method. For example, we might be writing a general-purpose class that will be used in a number of different programs. The ways that errors are reported to the user will differ according to the application. 

Here is an example. A class has been defined called FileManager() which contains useful methods for copying, renaming and deleting files. Clearly there is a need for exception handling here. The method copyFile() might be defined in outline something like this:

public void copyFile (String sourceFile, String destinationFile)

  {

  // more file read and write statements go here...

  }

This method will contain a lot of statements that generate exceptions. Where will they be handled? A typical scheme is to ‘pass upwards’ the exceptions. This means that the exceptions are not handled in this method, but in the method that called it. In this case the method that uses the copyFile() method must handle the exceptions (using try and catch as before).

The passing upwards of exceptions is indicated like this:

public void copyFile (String sourceFile, String destinationFile)

throws FileNotFoundException

  {

  // lots file read and write statements go here...

  }

Here ‘throws’ means that this method can itself throw an exception. If a FileNotFoundException occurs during the execution of copyFile() , then it is the method that called copyFile() that must handle it. copyFile() itself will stop as soon as the exception is detected. This means that if there are a long series of statements, and an exception occurs in the first one, then the rest of the method will be skipped.

Back to top

basicline.gif (169 bytes)

RITSEC - Global Campus
Copyright ?1999 RITSEC- Middlesex University. All rights reserved.
webmaster@globalcampus.com.eg