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

Introduction

Content

Apply

Reflect

Extend

previous.gif
 (3087 bytes)

next.gif
 (2959 bytes)

 

Content Index

Content Page # 28

File handling exceptions

File handling is an area where the programmer needs to take particular care that the program responds correctly if something unfortunate happens. For example, if we ask a word processor to open a file that does not exist, it should politely warn us of the problem. It should not crash, or print a meaningless error message like null pointer exception 0030:1023 in module aargh.exe’ ). The reason it responds appropriately is that the programmer anticipated that the user might make this mistake, and wrote program code to respond correctly. The programmer must provide program statements to deal with most or all errors and mis-operations that the program may encounter.

To simplify and regulate the process, Java uses a mechanism called ‘exception handling’. We have not covered this subject yet, but in brief it is a technique for specifying what can go wrong in any particular method. Java uses the statements throw , try and catch to control this process. 

For example, it was explained earlier in this unit how to define a BufferedReader , but this would not work as it standard because the code did not deal with the exceptions that might arise. When a method specifies that it might generate a particular exception, the program that uses it must take account of this. The compiler will not proceed otherwise. 

So this earlier section of Java should really have written like this:

try

  {

  File aFile = new File ("readme.txt");

  FileInputStream fis = new FileInputStream (aFile);

  InputStreamReader isr = new InputStreamReader (fis);

  BufferedReader br = new BufferedReader(isr);

  String aLine = br.readLine();

  }

catch (Exception e)

    {

    System.out.println ("Helpful error message");

    }

Here the keyword try means that the following section contains methods that are defined to produce exceptions (Java programmers talk about ‘throwing an exception’). The section starting with ‘ catch ’ defines what to do if one of these exceptions is actually generated.

The topic of exceptions is investigated in more detail later this unit.

Back to top

basicline.gif (169 bytes)

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