The Department of Computer Science & Engineering
cse@buffalo
STUART C. SHAPIRO: CSE 116 B

CSE 116
Introduction To Computer Science for Majors 2
Lecture B
Lecture Notes
Stuart C. Shapiro
Spring, 2003


Exceptions and File I/O

Reading
Riley, Chapters O4, O5

Introduction
We have already discussed throwing exceptions when preconditions are violated. These resulted in abnormal program termination.
Exceptions implement java.lang.Throwable.

Exception Handling
Can handle exceptions with a try statement:
      try {
        Statements during which one or more exceptions might be thrown.
      }
      catch (ExceptionType param) {       [optional]
        Code to handle exception.
      }
      catch (ExceptionType param) {       [optional]
        Code to handle exception.
      }
      catch (ExceptionType param) {       [optional]
        Code to handle exception.
      }
      finally {       [optional]
        Statements to be executed:
          after the try statements if no exception was thrown;
          after the code that caught an exception;
          after the try statements if an exception was thrown and not caught
      }
      Statements to be executed after the try statements when no exception is thrown,
        or after the catch code when an exception has been thrown.
        (Finally statements done first.)

Checked vs. Unchecked Exceptions and the throws Clause
The exceptions we have already used, are "unchecked" exceptions, as are all on Riley p. 544 except for IOException.
Unchecked exceptions need not be caught.

All "checked" exceptions must be planned for.
If a method might throw a checked exception, the code that calls that method must be in a try statement, or the method in which that code appears must be declared with a throws clause.

Object.clone() Now it can be told.
The clone method of the Cloneable interface throws the CloneNotSupportedException, which is checked, so if you implement and use clone, you need to use try and/or throws.

Programmer-Defined Exceptions
You may define your own exceptions by extending Exception (for checked exceptions), or RuntimeException (for unchecked exceptions).

File IO and Exceptions
Files are the paradigmatic sequential access collections. To access an element, you must first go through all earlier elements.
See Echo.java, List.java, and their documentation.

For different versions of the echo loop, see Echo2.java, and Echo3.java.

First Previous Next

Copyright © 2003 by Stuart C. Shapiro. All rights reserved.

Stuart C. Shapiro <shapiro@cse.buffalo.edu>