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

Introduction

Content

Apply

Reflect

Extend

previous.gif
 (3087 bytes)

next.gif
 (2959 bytes)

 

Content Index

Content Page # 41

Defining new exceptions

The standard built-in Java classes define and use exceptions. It is also possible to define new exceptions to organise exception handling for your own classes. Suppose, for example, we are writing a class that displays text files for the user to browse. It contains a method called ‘ openTextFile() ’ that reads a specified text file and displays it. If the user selects a file that is not a text file, the method cannot continue. We might define this method like this:

public void openTextFile(String textFileName)

  throws NotTextFileException

  {

  // Lots of file handling statements here

  }

The line:

throws NotTextFileException

indicates that this method can throw (generate) an exception called NotTextFileException ’. We have not defined yet what a NotTextFileException is.

When defining a new exception, we can make it a subclass of Exception, or of one of the existing subclasses of exception. With this example, NotTextFileException is similar to the existing file handling exceptions (like FileNotFoundException ) so we probably want to define it as a subclass of IOException (as the other file handling exceptions are). The definition will look like this:

class NotTextFileException extends IOException

  {

  }

This is the complete definition; in this case no methods are required.

So we know how to define an exception; how does the program throw it?

Back to top

basicline.gif (169 bytes)

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