Chapter 10.1

Chapter 10.1 - Chapter 10: Exceptions and I/O Chapter...

Info iconThis preview shows page 1. Sign up to view the full content.

View Full Document Right Arrow Icon
This is the end of the preview. Sign up to access the rest of the document.

Unformatted text preview: Chapter 10: Exceptions and I/O Chapter Streams Original Slides by John Lewis and William Loftus Original Modified significantly by Bob Roggio 1 Exceptions and I/O Streams Now we can explore two related topics further: Now exceptions and input/output streams exceptions Chapter 8 focuses on: Exception Handling Uncaught Exceptions The try-catch statement The finally Clause Exception propagation The Exception Class Hierarchy Checked and unchecked Exceptions I/O Exceptions I/O Streams 2/31 Exception Handling An exception is an object that describes an unusual or erroneous An exception object situation situation Exceptions are thrown by a program or the runtime environment, and thrown or may be caught and handled by another part of the program caught handled This means that when an exception occurs, you can sometimes code This what you want to happen. you want An exception is an object that defines unusual or erroneous An object situations. situations. An exception is something that should not normally happen or An happen infrequently. happen Your book has a list of common exceptions to be thrown. Array index out of bounds; Specified File cannot be Found; Division by Zero, … 3/31 Exception Handling As its name implies, exceptions are ‘exceptions’ to the normal way of doing business and we can design efficient ways to handle them if/when they occur. Program can deal with an exception in one of three ways: Program (Know this:) ignore it handle it where it occurs handle it an another place in the program The manner in which an exception is processed is an The important design consideration important 4/31 Exception Handling If an exception is ignored by the program, the program will If ignored terminate abnormally and produce an appropriate message terminate The message includes a call stack trace that indicates the line The call on which the exception occurred on You have no doubt seen these! The call stack trace also shows the method call trail that lead The call method to the attempted execution of the offending line to This has two parts: The getMessage method returns a string explaining why the The getMessage exception was thrown exception The printStackTrace method prints the call stack trace The printStackTrace 5/31 Example: Uncaught Exception // Author: Lewis/Loftus public class Zero { First line says that Exception was thrown. Other lines: Call trace (ahead) // Deliberately divides by zero to produce an exception. public static void main (String args) { int numerator = 10; int denominator = 0; the ‘object’ System.out.println (numerator / denominator); Call stack trace problem Exception class Method, file, and line number System.out.println ("This text will not be printed."); where exception occurred. }// end main() }// end Zero Exception in thread “main” java.lang.ArithmeticException: / by zero at Zero.main ( Note: tells problem and class.method (Zero and main) where it occurred and statement number! Note: 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 trace Can call methods in exception class: getMessage returns a string explaining reason for exception 6/31 printStackTrace prints the call stack trace. The try-catch Statement To process an exception when it occurs, the line that can cause To (throw) an exception is executed within a try block try A try block is followed by one or more catch clauses, which contain try one catch code to process an exception code The catch clauses are called exception handlers. The catch exception The try code is executed. This is where we put code that ‘could The cause us a problem.’ If all is well, execution continues following following any catch clauses present, which would be skipped. clauses If an exception occurs, processing continues at the first catch clause If catch that matches the exception type class. that Once the catch is executed, control returns to the next statement Once catch following the last catch clause. catch 7/31 public class ProductCodes // Author: Lewis / Loftus. Demo use of try-catch block. { Note: try-catch statements identify a public static void main (String args) { block of statements that might cause String code; (throw) an exception. char zone; int district, valid = 0, banned = 0; The catch statement (follows the try) Scanner scan – new Scanner (; tells how a particular kind of exception System.out.print ("Enter product code (XXX to quit): "); is handled. code = scan.nextLine(); catch statements called exception handlers while (!code.equals ("XXX")) Can have multiple catch clauses. { try { zone = code.charAt(9); If no problem in try, control resumes after district = Integer.parseInt(code.substring(3, 7)); last catch clause.. valid++; if (zone == 'R' && district > 2000) If an exception occurs and there is an banned++; appropriate exception handler for the } // end try catch (StringIndexOutOfBoundsException exception) exception class corresponding to the error. { System.out.println ("Improper code length: " + code); Control resumes following last catch clause. } // end catch catch (NumberFormatException exception) StringIndexOutOFBounds can be thrown by { charAt() or substring() methods. System.out.println ("District is not numeric: " + code); NumberFormatException can be thrown by } // end catch System.out.print ("Enter product code (XXX to quit): "); the parseInt method, if substring does not code = scan.nextLine(); contain a valid integer. } // end while System.out.println ("# of valid codes entered: " + valid); System.out.println ("# of banned codes entered: " + banned); The finally Clause A try statement can have an optional clause following the catch clauses, try catch designated by the reserved word finally finally The statements in the finally clause always are executed The always If no exception is generated, the statements in the finally clause are the executed after the statements in the try block complete after try If an exception is generated, the statements in the finally clause are the finally executed after the statements in the appropriate catch clause complete after complete A finally clause is sometimes used to ensure certain code executes no finally matter what… More later on this. matter 9/31 Exception Propagation An exception can be handled at a higher level if it is not An appropriate to handle it where it occurs Exceptions propagate up through the method-calling propagate up hierarchy until they are caught and handled or until they hierarchy reach the level of the method reach A try block that contains a call to a method in which an try call exception is thrown can be used to catch that exception exception See (page 546) See (page See (page 547) See (page Let’s look at some code… 10/31 10 //************************************************************ // 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. // // Demonstrates exception propagation. public class ExceptionScope { // Catches and handles the exception that is thrown in level3. An exception can be caught within the method public void level1() where the exception occurs. (try clause is found { within a method; ditto for catch clauses. System.out.println("Level 1 beginning."); try But, if a method calls another method and an { level2(); // transfers control to level2(). exception occurs there, that called method can }// end try handle the exception OR control can return to catch (ArithmeticException problem) // names the exception object the calling method that contains a try…catch { // names run-time exception class and object of that class. pair and be handled up there. System.out.println (); ========================================== System.out.println ("The exception message is: " + problem.getMessage()); Notice that we have System.out.println (); System.out.println ("The call stack trace:"); catch(ArithmeticException problem) problem.printStackTrace(); An exception (recall) is an object and thus System.out.println (); problem is an object of type ArithmeticException. }//end catch() So, we can call: System.out.println("Level 1 ending."); problem.getMessage() and problem.printStaceTrace() }// 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. Program beginning Level 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 ( at ExceptionScope.level2 ( at ExceptionScope.level1 ( Level1 ending Program ending. Note: control does not revert to the interrupted methods.! The Exception Class Hierarchy Important to note that all the classes that define the various exceptions are Important related by inheritance. (p.549) related See Object note: Throwable is parent to both Error and Exception! and many types of exceptions are derived from Exception class. and Throwable Throwable Error Error <Others> Exception RunTimeException ArithmeticException ArithmeticException IndexOutOFBoundsException IndexOutOFBoundsException NullPointerException NullPointerException <Others> There are many other child classes that define specific exceptions are part of other There packages. Inheritance relationships can span package boundaries. 14/31 14 The throw Statement Because Throwable is a base class and Exception Because Throwable Exception inherits from it, a programmer can define his/her own exceptions by extending the Exception class or one of extending Exception its descendants its Exceptions are ‘thrown’ using the throw statement Exceptions throw Usually a throw statement is nested inside an if Usually statement that evaluates the condition to see if the exception should be thrown exception Let’s see how we can create our own! We must derive Let’s our own class. our See (page 550) See (page See (page 551) See (page 15/31 15 //******************************************************************** // 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 (; 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 //******************************************************************** // 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! Checked Exceptions An exception is either checked or unchecked An exception checked unchecked A checked exception either must be caught by a checked method, or must be listed in the throws clause of any or throws method that may throw or propagate it method A throws clause is appended to the method header throws We are saying that if a problem occurs, the method will We throw an exception. throw (The compiler will issue an error if a checked exception is (The error not handled appropriately) not Example of checked exception: IOExceptions 18/31 18 Unchecked Exceptions An unchecked exception does not require explicit An handling, though it could be processed that way handling, The only unchecked exceptions in Java are objects of The type RuntimeException or any of its descendants RuntimeException ArithmeticException IndexOutOFBoundsException NullPointerException <Others> Errors are similar to RuntimeException and its Errors RuntimeException 19/31 19 Next three slides moved from last slides to here because Next we have used these objects and methods. we They do deal with the various kinds of streams that They follow this discussion though… follow 20/31 20 The IOException Class Operations performed by the I/O classes may throw an IOException Operations IOException A file intended for reading or writing might not exist Even if the file exists, a program may not be able to find it The file might not contain the kind of data we expect An IOException is a checked exception An checked In the next program, we create a file of test data from our program. In We use the FileWriter class to represent a text output file. We PrintWriter provides print and println methods to help FileWriter, which PrintWriter has minimal method support for manipulating data. has 21/31 21 // // Demonstrates the use of a character file output stream. import java.util.Random; import*; 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 Text Files Information can be read from and written to text files by Information declaring and using the correct I/O streams declaring The FileReader class represents an input file The FileReader containing character data containing The FileReader and BufferedReader classes The FileReader BufferedReader together create a convenient text file output stream just as we used FileWriter, BufferedWriter, and PrintWriter in the previous program. the 23/31 23 I/O Streams and I/O Exceptions A stream is a sequence of bytes that flow from a source to a destination stream In a program, we read information from an input stream and write In input stream information to an output stream output stream A program can manage multiple streams simultaneously There are three streams considered standard I/O streams. There standard System class contains three object reference variables: iin, out, err n, object that represent the three standard I/O streams. (public, static, so they can be accessed through the System class) can Have used standard output stream with calls to System.out.println and Have standard input stream when we used a Scanner object. By default, they represent particular I/O devices: keyboard input, By monitor screen output. (These could be changed) monitor 24/31 24 I/O Streams The package contains many classes that allow The us to define various other streams with particular other characteristics characteristics Some classes assume that the data consists of Some characters; other classes assume the data consists of characters other raw bytes of binary information. raw Some classes allow us to manipulate the data in the Some stream, such as buffering info or numbering it. By stream, By judiciously combining classes, we can represent a combining stream of information that has the characteristics we wish. wish This is a huge topic!!! 25/31 25 I/O Streams - Subdivisions Data stream acts as either a source or destination Processing stream - alters/manipulates basic data in the stream All kinds of opportunities for Input / Output Exceptions!!! Input Streams Output Streams Data Streams Processing Streams Character Streams Byte Streams 26/31 26 Character vs. Byte Streams A character stream manages 16-bit Unicode characters character A byte stream manages 8-bit bytes of raw binary data manages A program must determine how to interpret and use the bytes program interpret use in a byte stream in Typically they are used to read and write sounds and images The InputStream and OutputStream classes (and their The InputStream OutputStream descendants) represent byte streams descendants) The Reader and Writer classes (and their Reader Writer descendants) represent character streams character 27/31 27 Data vs. Processing Streams A data stream represents a particular source or destination such as a data string in memory or a file on disk string file A processing stream (also called a filtering stream) manipulates the processing filtering manipulates data in the stream data It may convert the data from one format to another It may buffer the stream It buffer We have used data streams when we have read files and data processing streams, when we have buffered the input streams! processing We must design our programs to be as resilient to these kinds of errors We as possible. They will occur! So we need to be able to handle them! will 28/31 28 ...
View Full Document

This note was uploaded on 07/26/2011 for the course COP 2551 taught by Professor Roggio,r during the Summer '08 term at UNF.

Ask a homework question - tutors are online