28
1 Chapter 10: Exceptions and Chapter 10: Exceptions and I/O Streams I/O Streams Original Slides by John Lewis and Original Slides by John Lewis and William Loftus William Loftus Modified significantly by Modified significantly by Bob Roggio, July 2007 Bob Roggio, July 2007

Chapter 10: Exceptions and I/O Streams

  • Upload
    oriel

  • View
    58

  • Download
    0

Embed Size (px)

DESCRIPTION

Chapter 10: Exceptions and I/O Streams. Original Slides by John Lewis and William Loftus Modified significantly by Bob Roggio, July 2007. Exceptions and I/O Streams. Now we can explore two related topics further: exceptions and input/output streams Chapter 8 focuses on: Exception Handling - PowerPoint PPT Presentation

Citation preview

Page 1: Chapter 10:  Exceptions and I/O Streams

11

Chapter 10: Exceptions and I/O Chapter 10: Exceptions and I/O Streams Streams

Original Slides by John Lewis and William LoftusOriginal Slides by John Lewis and William Loftus

Modified significantly byModified significantly by

Bob Roggio, July 2007Bob Roggio, July 2007

Page 2: Chapter 10:  Exceptions and I/O Streams

22/31/31

Exceptions and I/O StreamsExceptions and I/O Streams

Now we can explore two related topics further: exceptions Now we can explore two related topics further: exceptions and input/output streamsand input/output streams

Chapter 8 focuses on:Chapter 8 focuses on: Exception HandlingException Handling Uncaught ExceptionsUncaught Exceptions The try-catch statementThe try-catch statement The finally ClauseThe finally Clause Exception propagationException propagation The Exception Class HierarchyThe Exception Class Hierarchy

Checked and unchecked ExceptionsChecked and unchecked Exceptions I/O ExceptionsI/O Exceptions I/O StreamsI/O Streams

Page 3: Chapter 10:  Exceptions and I/O Streams

33/31/31

Exception HandlingException Handling

An An exceptionexception is an is an objectobject that describes an unusual or erroneous that describes an unusual or erroneous situationsituation

ExceptionsExceptions are are thrownthrown by a program by a program oror the runtime environment, and the runtime environment, and may be may be caughtcaught and and handledhandled by another part of the program by another part of the program

This means that when an exception occurs, you can sometimes code This means that when an exception occurs, you can sometimes code what you want to happen.what you want to happen.

An exception is an An exception is an objectobject that defines unusual or erroneous that defines unusual or erroneous situations.situations.

An exception is something that should not normally happen or An exception is something that should not normally happen or happen infrequently.happen infrequently.

Your book has a list of common exceptions to be thrown.Your book has a list of common exceptions to be thrown.

Array index out of bounds; specified file cannot be found; division by zero, …Array index out of bounds; specified file cannot be found; division by zero, …

Page 4: Chapter 10:  Exceptions and I/O Streams

44/31/31

Exception HandlingException Handling

As its name implies, exceptions are ‘exceptions’ to the As its name implies, exceptions are ‘exceptions’ to the normal way of doing business and we can design efficient normal way of doing business and we can design efficient ways to handle them if/when they occur. ways to handle them if/when they occur.

Program can deal with an exception in one of three ways:Program can deal with an exception in one of three ways:

ignore itignore it handle it where it occurshandle it where it occurs handle it an another place in the programhandle it an another place in the program

The manner in which an exception is processed is an The manner in which an exception is processed is an important design considerationimportant design consideration

Page 5: Chapter 10:  Exceptions and I/O Streams

55/31/31

Exception HandlingException Handling

If an exception is If an exception is ignoredignored by the program, the program will by the program, the program will terminateterminate abnormally and produce an appropriate message abnormally and produce an appropriate message

The message includes a The message includes a call stack tracecall stack trace that indicates the line that indicates the line on which the exception occurredon which the exception occurred

You have no doubt seen these!You have no doubt seen these!

The The call stack tracecall stack trace also shows the also shows the method call trailmethod call trail that lead that lead to the attempted execution of the offending lineto the attempted execution of the offending line

The The getMessagegetMessage method returns a string explaining why the method returns a string explaining why the exception was thrownexception was thrown

The The printStackTraceprintStackTrace method prints the call stack trace method prints the call stack trace

We will see these ahead.We will see these ahead.

Page 6: Chapter 10:  Exceptions and I/O Streams

66/31/31

// Zero.java Author: Lewis/Loftuspublic class Zero{

// Deliberately divides by zero to produce an exception. public static void main (String[] args) { int numerator = 10; int denominator = 0;

System.out.println (numerator / denominator);

System.out.println ("This text will not be printed."); }// end main()}// end ZeroOutput:Exception in thread “main” java.lang.ArithmeticException: / by zero at Zero.main (Zero.java:17) Note: tells problem and class.method where it occurred and statement number!There’s no code to handle this exception explicitly. The second System.out.println does not

execute, because the exception occurs first.First line says what exception was thrown and provides some info about why it was thrown.Remaining lines are the call stack traceCan call methods in exception class: getMessage returns a string explaining reason for exception printStackTrace prints the call stack trace.

Example: Uncaught Exception

Call stack traceproblemException class

First line says that Exception was thrown. Other lines: Call trace (ahead)

Method, file, and line number where exception occurred.

Page 7: Chapter 10:  Exceptions and I/O Streams

77/31/31

The try-catch StatementThe try-catch StatementTo process an exception when it occurs, the line that can cause To process an exception when it occurs, the line that can cause (throw) an exception is executed within a (throw) an exception is executed within a try blocktry block

A try block is followed by A try block is followed by one or moreone or more catchcatch clauses, which contain clauses, which contain code to process an exceptioncode to process an exception

The catch clauses are called exception handlers.The catch clauses are called exception handlers.

The The try try code is executed. If all is well, execution continues code is executed. If all is well, execution continues following any following any catch catch clauses present.clauses present.

If an exception occurs, processing continues at the first If an exception occurs, processing continues at the first catchcatch clause that matches the exception type class.clause that matches the exception type class.

Once the Once the catchcatch is executed, control returns to the next statement is executed, control returns to the next statement following the last following the last catchcatch claus claus

Page 8: Chapter 10:  Exceptions and I/O Streams

public class ProductCodes // Author: Lewis / Loftus. Demo use of try-catch block.{ public static void main (String[] args) { String code; char zone; int district, valid = 0, banned = 0; Scanner scan – new Scanner (System.in); System.out.print ("Enter product code (XXX to quit): "); code = scan.nextLine(); while (!code.equals ("XXX")) { try { zone = code.charAt(9); district = Integer.parseInt(code.substring(3, 7)); valid++; if (zone == 'R' && district > 2000) banned++; } // end try catch (StringIndexOutOfBoundsException exception) { System.out.println ("Improper code length: " + code); } // end catch catch (NumberFormatException exception) { System.out.println ("District is not numeric: " + code); } // end catch System.out.print ("Enter product code (XXX to quit): "); code = Keyboard.readString(); } // end while System.out.println ("# of valid codes entered: " + valid); System.out.println ("# of banned codes entered: " + banned); } // end main()} // end class

Note: try-catch statements identify a block of statements that might cause(throw) an exception.The catch statement (follows the try) tells how a particular kind of exception is handled.catch statements called exception handlersCan have multiple catch clauses.

If no problem in try, control resumes after last catch clause..

If an exception occurs and there is an appropriate exception handler for the exception class corresponding to the error.

Control resumes following last catch clause.

StringIndexOutOFBounds can be thrown by charAt() or substring() methods. NumberFormatException can be thrown by the parseInt method, if substring does not contain a valid integer.

Page 9: Chapter 10:  Exceptions and I/O Streams

99/31/31

The finally ClauseThe finally Clause

A try statement can have an optional clause following the catch clauses, A try statement can have an optional clause following the catch clauses, designated by the reserved word designated by the reserved word finallyfinally

The statements in the finally clause The statements in the finally clause alwaysalways are executed are executed

If no exception is generatedIf no exception is generated, the statements in the finally clause are , the statements in the finally clause are executed after the statements in the try block completeexecuted after the statements in the try block complete

If an exception is generatedIf an exception is generated, the statements in the finally clause are , the statements in the finally clause are executed after the statements in the appropriate catch clause completeexecuted after the statements in the appropriate catch clause complete

A finally clause is sometimes used to ensure certain code executes no A finally clause is sometimes used to ensure certain code executes no matter what… More later on this.matter what… More later on this.

Page 10: Chapter 10:  Exceptions and I/O Streams

1010/31/31

Exception PropagationException Propagation

An exception can be handled at a higher level if it is not An exception can be handled at a higher level if it is not appropriate to handle it where it occurs appropriate to handle it where it occurs

Exceptions Exceptions propagatepropagate up throughup through the the method-calling method-calling hierarchyhierarchy until they are caught and handled or until they until they are caught and handled or until they reach the level of the methodreach the level of the method

A try block that contains a A try block that contains a callcall to a method in which an to a method in which an exception is thrown can be used to catch that exceptionexception is thrown can be used to catch that exception

See See Propagation.javaPropagation.java (page 546)(page 546)

See See ExceptionScope.javaExceptionScope.java (page 547)(page 547)

Let’s look at some code…Let’s look at some code…

Page 11: Chapter 10:  Exceptions and I/O Streams

//************************************************************// Propagation.java Author: Lewis/Loftus//// Demonstrates exception propagation.//************************************************************

public class Propagation{ //----------------------------------------------------------------- // Invokes the level1 method to begin the exception demonstration. //----------------------------------------------------------------- static public void main (String[] args) { ExceptionScope demo = new ExceptionScope();

// creates object of type demo. System.out.println("Program beginning."); demo.level1(); // invokes demo.level1() System.out.println("Program ending."); }// end main()}// end Propagation class.

Page 12: Chapter 10:  Exceptions and I/O Streams

// ExceptionScope.java // Demonstrates exception propagation.public class ExceptionScope{ // Catches and handles the exception that is thrown in level3. public void level1() { System.out.println("Level 1 beginning."); try { level2(); // transfers control to level2(). }// end try catch (ArithmeticException problem) { System.out.println (); System.out.println ("The exception message is: " + problem.getMessage()); System.out.println (); System.out.println ("The call stack trace:"); problem.printStackTrace(); System.out.println (); }//end catch() System.out.println("Level 1 ending."); }// end level1() // Serves as an intermediate level. The exception propagates through this method back to level1 public void level2() { System.out.println("Level 2 beginning."); level3 (); // transfers control to level 3(). System.out.println("Level 2 ending."); }// end level 2() // Performs a calculation to produce an exception. It is not caught and handled at this level. public void level3 () { int numerator = 10, denominator = 0; // OK. Here’s the obvious error. Note: no exception handler in level 3() System.out.println("Level 3 beginning."); // To catch an exception at a higher level, the method with the exception int result = numerator / denominator; // must be invoked inside a try block that has a catch clause to handle exception. System.out.println("Level 3 ending."); // Control is passed up to level2(). But no handler here; control passes to level1() } // end level3() // Because level2() is invoked inside a try block that has a catch clause to handle}// end class // the exception, the exception is caught and handled now.

// Note that the last System.out.println statements are not executed! Once caught, the level1() ‘ending’ message executes.

An exception can be caught within the method where the exception occurs. (try clause is found within a method; ditto for catch clauses.

But, if a method calls another method and an exception occurs there, that called method can handle the exception OR control can return to the calling method that contains a try…catch pair and be handled up there.==========================================Notice that we have catch(ArithmeticException problem)An exception (recall) is an object and thus problem is an object of type ArithmeticException.So, we can call:problem.getMessage() and problem.printStaceTrace()

Page 13: Chapter 10:  Exceptions and I/O Streams

Program beginningLevel 1 beginning.Level 2 beginning.Level 3 beginning.

The exception message is: / by zero

The call stack trace:java.lang.ArithmeticException: / by zero

at ExceptionScope.level3 (ExceptionScope.java:54)at ExceptionScope.level2 (ExceptionScope.java.41)at ExceptionScope.level1 (ExceptionScope.java:18)

Level1 endingProgram ending.

Note: control does not revert to the interrupted methods.!

Page 14: Chapter 10:  Exceptions and I/O Streams

1414/31/31

The Exception Class HierarchyThe Exception Class Hierarchy

Important to note that all the classes that define the various exceptions are related by Important to note that all the classes that define the various exceptions are related by inheritance. (p.549)inheritance. (p.549)See Object note: Throwable is parent to both Error and Exceptin!See Object note: Throwable is parent to both Error and Exceptin!

and many types of exceptions are derived from Exception classand many types of exceptions are derived from Exception class ..

ThrowableThrowable

ErrorError Exception Exception

<Others><Others> RunTimeExceptionRunTimeException

ArithmeticExceptionArithmeticException IndexOutOFBoundsExceptionIndexOutOFBoundsException

NullPointerExceptionNullPointerException<Others><Others>

There are There are many other child classes that define specific exceptions are part of other many other child classes that define specific exceptions are part of other packages. Inheritance relationships can span package boundaries. packages. Inheritance relationships can span package boundaries.

Page 15: Chapter 10:  Exceptions and I/O Streams

1515/31/31

The throw StatementThe throw StatementBecause Because ThrowableThrowable is a base class and is a base class and ExceptionException inherits inherits from it, a programmer can define his/her own exceptions by from it, a programmer can define his/her own exceptions by extendingextending the the ExceptionException class or one of its descendants class or one of its descendants

Exceptions are ‘thrown’ using the Exceptions are ‘thrown’ using the throwthrow statement statement

Usually a throw statement is nested inside an if statement Usually a throw statement is nested inside an if statement that evaluates the condition to see if the exception should be that evaluates the condition to see if the exception should be thrownthrown

Let’s see how we can create our own! We must derive our Let’s see how we can create our own! We must derive our own class.own class.

See See CreatingExceptions.javaCreatingExceptions.java (page 550)(page 550)

See See OutOfRangeException.javaOutOfRangeException.java (page 551)(page 551)

Page 16: Chapter 10:  Exceptions and I/O Streams

//********************************************************************// CreatingExceptions.java Author: Lewis/Loftus//// Demonstrates the ability to define an exception via inheritance.//********************************************************************public class CreatingExceptions{ // Creates an exception object and possibly throws it. public static void main (String[] args) throws OutOfRangeException { // This is not part of the standard Java library! final int MIN = 25, MAX = 40; Scanner scan = new Scanner (System.in); OutOfRangeException problem = // object is created (inheritance) and initialized. new OutOfRangeException ("Input value is out of range.");

System.out.print ("Enter an integer value between " + MIN + " and " + MAX + ", inclusive: "); int value = scan.nextInt(); // Determines if the exception should be thrown if (value < MIN || value > MAX) throw problem; System.out.println ("End of main method."); // may never reach }// end main()}// end CreatingEXceptions

Page 17: Chapter 10:  Exceptions and I/O Streams

//********************************************************************// OutOfRangeException.java Author: Lewis/Loftus//// Represents an exceptional condition in which a value is out of// some particular range.//********************************************************************

public class OutOfRangeException extends Exception Here we are creating OUR OWN{ Exception Handler (like ArrayIndexOutOfRange) //----------------------------------------------------------------- by extending the object, Exception. // Sets up the exception object with a particular message. //----------------------------------------------------------------- OutOfRangeException (String message) { super (message); } // end of OUtOFRangeException method()}//end class OutOfRangeException

This is a simple example, but is very typical when we want to trap and process our own potential errors.But it is important to note that this class is derived from Exception which is derived from Throwable..

Throwable provides the ability to use the throw statement!

There are other simple ways to accommodate an input error such as this. A simple if statement can check and provide a message; alternatively, you may design your own Exceptions!

Page 18: Chapter 10:  Exceptions and I/O Streams

1818/31/31

Checked ExceptionsChecked Exceptions

An exception is either An exception is either checkedchecked or or uncheckedunchecked

A A checked exceptionchecked exception either must be caught by a method, either must be caught by a method, oror must be listed in the must be listed in the throws clausethrows clause of any method that of any method that may throw or propagate itmay throw or propagate it

A A throwsthrows clause is appended to the method header clause is appended to the method header

We are saying that if a problem occurs, the method will We are saying that if a problem occurs, the method will throw an exception.throw an exception.

The compiler will issue an The compiler will issue an errorerror if a checked exception is if a checked exception is not handled appropriatelynot handled appropriately

Page 19: Chapter 10:  Exceptions and I/O Streams

1919/31/31

Unchecked ExceptionsUnchecked Exceptions

An unchecked exception does not require explicit handling, An unchecked exception does not require explicit handling, though it could be processed that waythough it could be processed that way

The only unchecked exceptions in Java are objects of type The only unchecked exceptions in Java are objects of type RuntimeExceptionRuntimeException or any of its descendants or any of its descendants

Errors are similar to Errors are similar to RuntimeExceptionRuntimeException and its and its descendantsdescendants

Errors should not be caughtErrors should not be caught

Errors to not require a throws clauseErrors to not require a throws clause

Page 20: Chapter 10:  Exceptions and I/O Streams

2020/31/31

Next three slides moved from last slides to here because Next three slides moved from last slides to here because we have used these objects and methods.we have used these objects and methods.

They do deal with the various kinds of streams that They do deal with the various kinds of streams that follow this discussion though…follow this discussion though…

Page 21: Chapter 10:  Exceptions and I/O Streams

2121/31/31

The IOException ClassThe IOException ClassOperations performed by the I/O classes may throw an Operations performed by the I/O classes may throw an IOExceptionIOException

A file intended for reading or writing might not existA file intended for reading or writing might not exist

Even if the file exists, a program may not be able to find itEven if the file exists, a program may not be able to find it

The file might not contain the kind of data we expectThe file might not contain the kind of data we expect

An IOException is a An IOException is a checkedchecked exception exception

In the next program, we create a file of test data from our program. In the next program, we create a file of test data from our program.

We use the FileWriter class to represent a text output file.We use the FileWriter class to represent a text output file.

PrintWriter provides print and println methods to help FileWriter, which PrintWriter provides print and println methods to help FileWriter, which has minimal method support for manipulating data.has minimal method support for manipulating data.

Page 22: Chapter 10:  Exceptions and I/O Streams

// TestData.java // Demonstrates the use of a character file output stream.import java.util.Random; import java.io.*;public class TestData{ // Creates a file of test data that consists of ten lines each containing ten integer values in range 10-99. public static void main (String[] args) throws IOException { final int MAX = 10; int value; Random rand = new Random(); String file = "test.dat"; // creating a String object, file, that contains the name of the external file. FileWriter fw = new FileWriter (file); BufferedWriter bw = new BufferedWriter (fw); PrintWriter outFile = new PrintWriter (bw); // PrintWriter contains methods print(), println(), close()…// all these work together. Have added a layer in the file stream configuration to include a //BufferedWriter object, bw. This simply gives the output stream buffering capabilities which makes the processing more efficient. Buffering is always recommended in writing text files.Note how the objects from one action are fed as input parameters to the next!! for (int line=1; line <= MAX; line++) { for (int num=1; num <= MAX; num++) { value = rand.nextInt (90) + 10; outFile.print (value + " "); }// end inner for outFile.println (); // note we have not supplied an IOException handler. Thus, if anything goes } // end outer for // wrong, we will allow the program to terminate. outFile.close(); // Because all IOExcpetions areh checked exceptions, we must include the System.out.println ("Output file has been created: " + file); // throws clause on the method header to indicate }// end main() // that they may be thrown. } // end class TestData

Page 23: Chapter 10:  Exceptions and I/O Streams

2323/31/31

Text FilesText Files

Information can be read from and written to text files by Information can be read from and written to text files by declaring and using the correct I/O streamsdeclaring and using the correct I/O streams

The The FileReaderFileReader class represents an input file class represents an input file containing character datacontaining character data

The The FileReaderFileReader and and BufferedReaderBufferedReader classes classes together create a convenient text file output stream just together create a convenient text file output stream just as we used FileWriter, BufferedWriter, and PrintWriter in as we used FileWriter, BufferedWriter, and PrintWriter in the previous program.the previous program.

Page 24: Chapter 10:  Exceptions and I/O Streams

2424/31/31

I/O Streams and I/O ExceptionsI/O Streams and I/O Exceptions

A A streamstream is a sequence of bytes that flow from a source to a destination is a sequence of bytes that flow from a source to a destination

In a program, we read information from an In a program, we read information from an inputinput streamstream and write and write information to an information to an outputoutput streamstream

A program can manage multiple streams simultaneouslyA program can manage multiple streams simultaneously

There are three streams considered There are three streams considered standard I/O streams.standard I/O streams.

SystemSystem class contains three class contains three object reference variablesobject reference variables: in, out, err : in, out, err that represent the three standard I/O streams. (public, static, so they that represent the three standard I/O streams. (public, static, so they can be accessed through the System class)can be accessed through the System class)

Have used standard output stream with calls to System.out.println and Have used standard output stream with calls to System.out.println and standard input stream when we used a Scanner object. standard input stream when we used a Scanner object.

By default, they represent particular I/O devices: keyboard input, By default, they represent particular I/O devices: keyboard input, monitor screen output. (These could be changed)monitor screen output. (These could be changed)

Page 25: Chapter 10:  Exceptions and I/O Streams

2525/31/31

I/O StreamsI/O StreamsThe The java.iojava.io package contains many classes that allow us package contains many classes that allow us to define various to define various otherother streams with particular characteristics streams with particular characteristics

Some classes assume that the data consists of Some classes assume that the data consists of characterscharacters; ; other classes assume the data consists of other classes assume the data consists of raw bytes of raw bytes of binary informationbinary information..

Some classes allow us to manipulate the data in the Some classes allow us to manipulate the data in the stream, such as buffering info or numbering itstream, such as buffering info or numbering it. By . By judiciously judiciously combiningcombining classes, we can represent a classes, we can represent a stream of information that has the characteristics we stream of information that has the characteristics we wishwish..

This is a huge topic!!!This is a huge topic!!!

Page 26: Chapter 10:  Exceptions and I/O Streams

2626/31/31

I/O Streams - SubdivisionsI/O Streams - Subdivisions

CharacterStreams

ByteStreams

DataStreams

ProcessingStreams

Input Streams

Output Streams

Data stream acts as either a source or destinationProcessing stream - alters/manipulates basic data in the stream

All kinds of opportunities for Input / Output Exceptions!!!

Page 27: Chapter 10:  Exceptions and I/O Streams

2727/31/31

Character vs. Byte StreamsCharacter vs. Byte Streams A A character streamcharacter stream manages 16-bit Unicode characters manages 16-bit Unicode characters

A A byte stream byte stream manages 8-bit bytes of raw binary datamanages 8-bit bytes of raw binary data

A program must determine how to A program must determine how to interpretinterpret and and useuse the bytes the bytes in a byte streamin a byte stream

Typically they are used to read and write sounds and imagesTypically they are used to read and write sounds and images

The The InputStreamInputStream and and OutputStreamOutputStream classes (and their classes (and their descendants) represent byte streamsdescendants) represent byte streams

The The ReaderReader and and WriterWriter classes (and their classes (and their descendants) represent descendants) represent charactercharacter streams streams

Page 28: Chapter 10:  Exceptions and I/O Streams

2828/31/31

Data vs. Processing StreamsData vs. Processing StreamsA A data streamdata stream represents a particular source or destination such as a represents a particular source or destination such as a stringstring in memory or a in memory or a filefile on disk on disk

A A processing streamprocessing stream (also called a (also called a filtering streamfiltering stream) ) manipulatesmanipulates the the data in the streamdata in the stream

It may convert the data from one format to anotherIt may convert the data from one format to another

It may It may bufferbuffer the stream the stream

We have used We have used data streamsdata streams when we have read files and when we have read files and processing streamsprocessing streams, when we have buffered the input streams!, when we have buffered the input streams!

We must design our programs to be as resilient to these kinds of errors We must design our programs to be as resilient to these kinds of errors as possible. They as possible. They will occur!will occur! So we need to be able to handle them! So we need to be able to handle them!