<<

Computer Science II 4003-232-07 (Winter 2007-2008) Exceptions and

Week 3: Exceptions, Wrapper Classes, Streams, File I/O

Richard Zanibbi Rochester Institute of Technology

Three Types of Programming Errors Examples of Runtime Errors (Exceptions) Syntax Errors – Source code (e.g. Java program) is not well-formed, i.e. • Invalid input does not follow the rules of the language. – Normally caught by a language compiler (e.g. javac) • Attempt to open file that doesn’t exist • Network connection broken Logic Errors – Program does not express the operations that the • Array index out of bounds programmer intended. – Addressed through testing (to catch logical errors) and (to fix logical errors).

Runtime Errors (“Exceptions”) During program , the program requests an operation that is impossible to carry out. - 3 - - 4 -

Catching and Handling Exceptions Method and

Method Call Stack (“Call Stack”) Catching Exceptions – The stack that records data associated with the current method being executed (top of the stack), as well that for the chain of Allowing a program to receive an indication of the method calls that led to the current method state of execution when a runtime error occurs, and the type of error detected. Stack Trace – A summary of the contents of the call stack (from top to bottom) – Normally listed from most (top) to least (bottom) recent method. main() is usually at the bottom of the method call stack. Handling Exceptions – Usually source line numbers for statements that invoke a method Code is associated with caught exceptions in and the last statement executed in the current method are given. – If an exception is not caught, a Java program will display the order to allow a program to recover from and/or exception followed by a stack trace (e.g. ExceptionDemo.java, repair the problem. p.578); the first (active) method will have thrown the exception

- 5 - - 6 -

1 Catching and Handling Exceptions in Types of Exceptions in Java Java: the try-catch Block System Errors (Error) The Basic Idea – Thrown by the (JVM) Define 1) a scope for a of commands that may – Internal system errors (rare), such as incompatability produce exceptions (‘try’), and 2) a subsequent list of between class files, JVM failures exception handlers to invoke when exceptions of different types are thrown (‘catch’). Runtime Exceptions (RuntimeException) – Also normally thrown by JVM in a ‘try-catch’ Block – Usually unrecoverable programming errors (e.g. divide – When an exception occurs in a ‘try’ block, execution by 0, array index error, null reference) jumps to the end of the ‘try’ block (end brace ‘}’ ). – Java then tries to match the exception type against the list of ‘catch’ statements in order, to find a handler for the (“Normal”) Exceptions (Exception) exception. (Example: HandleExceptionDemo.java, p. 579) – Errors that may be caught and handled (e.g. file not found) - 7 - - 8 -

Unchecked and Checked Exceptions

Unchecked Exceptions – Error, RuntimeException, and subclasses – These exceptions are normally not recoverable (cannot be handled usefully, e.g. NullPointerException) – The javac compiler does not force these exceptions to be declared or caught (to keep programs simpler), but they can be.

Checked Exceptions – Exception class and subclasses (excluding RuntimeException) – Compiler forces the programmer to catch and handle these. Why?

- 9 - - 10 -

Catching Exceptions Declaring and Throwing Exceptions Using try-catch

try { // statements that might throw an exception statement1; Exception Type If exception occurs, jump out of statement2; try block before next instruction } catch (Exception1 e1) { // handler for Exception1 } If exception occurred, search for matching catch (Exception2 e2) { exception type (‘catch’ it), execute // handler for Exception2 associated handler. Then execute first } statement after catch blocks. ... (NOTE: exceptions must be listed from • “Throwing” an exception means to use the “throw” command to generate catch {ExceptionN eN) { most to least specific class) // handler for ExceptionN a message (an object that is a subclass of Exception) } ** At most one handler is executed. • “Declaring” an exception means to add it to a list of (checked) exceptions at the end of a method signature, e.g. // Statements after try-catch If no ‘catch’ matches the exception, nextStatement; public void myMethod() throws Exception1, ...., ExceptionN { ... } the exception is passed back to the calling method, and the current this is required if a method may throw but not catch an exception - 11 - method is exited. - 12 -

2 Getting Information from Exceptions

Example: TestException.java (p. 586)

Cases to consider: in method2, throwing Exception3, Exception2, Exception1, (The message is a text string associated with the SomeOtherException objects (each type being a subclass of ‘Exception’) Throwable object (e.g. exception))

- 13 - - 14 -

Example: Declaring, Throwing, and Addition to try-catch: Catching Exceptions the finally clause (try-catch-finally) From Text Purpose CircleWithException.java –Define a block of code that will execute regardless of whether an exception is caught or not for a try block TestCircleWithException.java (p. 588) (executes after try and catch blocks) –Finally block will execute even if a *setRadius() method redefined to throw a precedes it in a try block or catch block (!) (built-in) IllegalArgumentException Example Uses I/O programming: ensure that a file is always closed. *The message string is passed to the constructor for IllegalArgumentException Also a way to define error-handling code common to different error types in one place within a method.

- 15 - - 16 -

FinallyDemo.java (p. 590 in text) When Do I Use Exceptions?

(text, p. 591) “The point is not to abuse exception public class FinallyDemo { handling as a way to deal with a simple logic test.” public static void main(String[] args) { java.io.PrintWriter output = null; try { System.out.println(refVar.toString()); } try { // Create a file catch (NullPointerException ex) { System.out.println(“refVar is null”);} output = new java.io.PrintWriter("text.txt"); Requires creation of a NullPointerException vs. // Write formatted output to the file object, propogating the exception output.println("Welcome to Java"); } if (refVar != null) catch (java.io.IOException ex) { ex.printStackTrace(); System.out.println(refVar.toString()); } else finally { System.out.println(“refVar is null”); // Close the file if (output != null) output.close(); }}} Use exceptions for ‘unexpected’ errors (unusual situations). Simple errors specific to a method should be handled within the method

- 17 - (locally), as above. - 18 -

3 public class InvalidRadiusException extends Exception { Defining New Exception Classes private double radius;

/** Construct an exception */ Java Exception Classes public InvalidRadiusException(double radius) { Are numerous; use these where possible. super("Invalid radius " + radius); this.radius = radius; } New Exception Classes /** Return the radius */ Are derived from Exception or a subclass of exception. public double getRadius() { return radius; } Constructors for Exception Classes } Constructors are normally either no-arg, or one argument Example Use: (takes the string message as an argument) throw new InvalidRadiusException(-5.0);

- 19 - - 20 -

Exercise: Exceptions H. try { statement1; A. What is a runtime error? statement2; B. What is a checked exception? What is an statement3; unchecked exception? } . What are the keywords ‘throw’ and ‘throws’ catch (Exception1 ex1) { statement4; } used for? catch (Exception2 ex2) { statement5; } finally { statement6; } . What is the purpose of supporting exceptions statement7; within Java (in one sentence)? E. What happens if an exception is thrown within For each of the following, indicate which statements in the above a method, but not caught? code would be executed. F. When will an exception terminate a program? 1. statement2 throws an Exception1 exception 2. statement2 throws an Exception2 exception G. In what order must “catch” blocks be 3. statement2 throws an Exception3 exception organized? 4. No exception is thrown. - 21 - - 22 -

Primitive Data Types

Include... Wrapper Classes for , short, int, long, float, double char Primitive Types boolean

(text Ch 10.5) Why aren’t these objects? A. Efficiency (avoid “object overhead”)

- 24 -

4 Wrapper Classes UML Class Diagram for Wrapper Classes

...but sometimes it would be useful to have objects hold primitive data.

Example To include different primitive data types in a single Object[] array.

Wrapper Classes – Classes for “wrapping” primitive data in objects. – All override the Object methods toString, equals, and hashCode. – All wrapper classes (except for Boolean) implement the NOTE: all wrapper classes capitalize the name of the Comparable (implement compareTo) associated primitive type, except for Integer and .

- 25 - - 26 -

Example: Constructing Wrapped Numbers

Double doubleObject = new Double(5.0); Double doubleObject = new Double(“5.0”); Double doubleObject = Double.valueOf(“12.4”)

Integer intObject = new Integer(5); Integer intObject = new Integer(“5”); Integer intObject = Integer.valueOf(“12”);

NOTE: valueOf is a static method defined for all numeric wrapper classes.

- 27 - - 28 -

Converting Between Strings and Example: A Polymorphic (“Generic”) Primitive Numeric Types Sorting Method Converting to String Text page 360, GenericSort.java Double doubleObject = new Double(5.0); (an implementation of Selection Sort: iteratively String s = doubleObject.toString(); finds largest element, places at end of array)

Converting from String • Using the Comparable interface (compareTo()), different object types are double d = Double.parseDouble(“5.0”); sorted using the same sorting function. int i = Integer.parseInt(“5”); • NOTE: Java defines a static sort in the Arrays // Using ‘parse’ method with a radix (base): class, for any array of objects, e.g. int j = Integer.parseInt(“11”, 2); // j = 3 java.util.Arrays.sort(intArray);

- 29 - - 30 -

5 Automatic Conversion Between Primitive and Wrapper Class Types (JDK 1.5) Exercise: Wrapper Classes

Boxing A. What are the names of the wrapper Converting primitive → wrapper classes? e.g. Integer[ ] intArray = {1, 2, 3}; B. What is boxing and unboxing? e.g. Integer intObject = 2; // both legal, ‘autoboxing’ occurs C. Which of the following are illegal? 1. Number x = 3; Unboxing 2. Integer x = 3; Converting wrapper → primitive e.g. System.out.println(intArray[0] + intArray[1] + intArray[2]); 3. Double x = 3; // int values are summed before output. 4. Double x = 3.0; e.g. int i = new Integer(3); // legal, ‘autounboxing occurs’ 5. int x = new Integer(3); 6. int x = new Integer(3) + new Integer(4); Automatic Conversions 7. double y = 3.4; – Compiler will box for contexts requiring an object 8. y.intValue(); – Compiler will unbox for contexts requiring a primitive - 31 - - 32 -

Operating System Organization

File Manager Process, & Streams and Files Resource Manager

Memory Device Manager Manager

Processor(s) Main Memory Devices

- 34 -

The External View of the File Manager File Directories

Application Program File Directory

mount() A set of files and other (sub)directories write() WriteFile() CreateFile() close()open() ReadFile() Principle function: help people find their way read() CloseHandle() lseek() SetFilePointer() around data on a system r r r r r r g g g g g g r r M M g g M M

M M

y y s s M M e e r r s s

c c o e e o e e i i l l c c Implementation i i v v m m o o e e F F e e r r D D P P M M Directories are stored as additional files UNIX Windows

Hardware

- 35 - - 36 -

6 Directory Structures Absolute and Relative Paths

Absolute Path D D D F Path from the root (top) directory in a directory tree to the desired directory/file F D D D D • e.g. “/home/zanibbi/comp232/slides.ppt” ... • e.g. “D:\myfiles\zanibbi\comp232\slides.ppt” D F F F F F F F F F Flat Relative Path Acyclic Graph F F F Path from (“relative to”) a given directory • (usually current) Strict Hierarchy • e.g. : “comp232/slides.ppt” (from /home/zanibbi) (“Directory Tree”) D = Directory • e.g. : “comp232\slides.ppt” (from D:\myfiles\zanibbi) F = File

- 37 - - 38 -

Example: DOS File Directory Example: Unix File Directory

“This Machine” (usually implicit root directory of file system) Directed Acyclic Graphs Root Directory: “/” (e.g. “cd /”) A:\ B:\ C:\ D:\ (Disk Drive D)

...... USER / GJN PROGRAMS home etc lib bin BIN AUTOEXEC.BAT PRIME.C zanibbi wasserman PATCH comp232

slides.ppt - 39 - - 40 -

File Class in Java Writing to Text Files in Java Using PrintWriter Purpose – Represent attributes of files (from file descriptors in directories) PrintWriter Allows programmer to use the same print, println, and printf – May be used to rename or delete files commands used with System.out, but sends data to a file rather – Directories may also be represented using a File object than the standard output. – ** Not used to read and write file data Opening a File for Writing Path Separators (“\\” and “/”) PrintWriter outputFile = new PrintWriter(“FileInCurrentDir.txt”); – Because “\” is an escape character in Java Strings, directory separators for Windows must be indicated using “\\” – e.g. “C:\\book\\Welcome.java” Important – It is important to explicitly close() a file, to make sure that the data – When giving relative paths in Java, you can use “/”, as on Unix written is properly saved, and to release resources needed for the systems (works for all platforms). This is recommended. file. – e.g. outputFile.close(); Example TestFileClass.java (p. 285) Example - 41 - WriteData.java (p. 286) - 42 -

7 Reading Text Files in Java Using Scanner Scanner Reads input from a text file one token at a time. A token is a series of adjacent non-whitespace characters (newlines, spaces, tabs separate tokens)

Opening a File for Reading Scanner stdIn = new Scanner(Standard.in); - Standard.in is the standard input, a file defined for all programs running on a machine. Usually the standard input contains captured keyboard strokes. Scanner input = new Scanner(new File(“FileName.txt”));

Example ReadData.java (p. 287)

- 43 -

8