Unformatted text preview:

Topic 4E ti d Fil I/OExceptions and File I/O"A slipping gear could let your M203A slipping gear could let your M203 grenade launcher fire when you least expect it. That would make you quite unpopular in what's left of your unit"unpopular in what s left of your unit.- THE U.S. Army's PS magazine, August 1993, quoted in The Java Programming Language, 3rd editionCS 307 Fundamentals of Computer ScienceJava Basics - Exceptions and File I/O1When Good Programs Go Bad8Aitf h8A variety of errors can occur when a program is running. For example:(l) i t bdl–(real) user input error. bad url– device errors. remote server unavailablephysical limitations full disk–physical limitations. full disk– code errors. interact with code that does not fulfill its contact (pre and post conditions)its contact (pre and post conditions)8when an error occurs–return to safe state save work exit gracefullyreturn to safe state, save work, exit gracefully8error handling code may be far removed from code that caused the errorCS 307 Fundamentals of Computer ScienceJava Basics - Exceptions and File I/O2from code that caused the errorHow to Handle Errors?88It is possible to detect and handle errors of various types.8Problem: this complicates the code and makes it harder to understand.– the error detection and error handling code have little or nothing to do with the real code is trying to do.8A tradeoff between ensuring correct behavior under all possible circumstances and clarity of the codeCS 307 Fundamentals of Computer ScienceJava Basics - Exceptions and File I/O3Exceptions88Many languages, including Java use a mechanism know as Exceptions to handle errors at runtime– In Java Exception is a class with many descendants.– ArrayIndexOutOfBoundsException–NullPointerException– FileNotFoundException– ArithmeticException– IllegalArgumentExceptionCS 307 Fundamentals of Computer ScienceJava Basics - Exceptions and File I/O4Partial Exceptions HierarchyTh blThrowableErrorE ceptionIOE tiRti E tiErrorExceptionIOExceptionRuntimeExceptionEOFException FileNotFoundExceptionAdArithmeticExceptionNullPointerExceptionIndexOutofBoundsIllegalArgumentAnd many, many, many moreCS 307 Fundamentals of Computer ScienceJava Basics - Exceptions and File I/O5Exception Exceptionmore…Creating Exceptions88As a program runs, if a situation occurs that is handled by exceptions then an Exception is thrown.– An Exception object of the proper type is created– flow of control is transferred from the current block of code to code that can handle or deal ith th tiwith the exception– the normal flow of the program stops and error handling code takes o er (if it e ists )handling code takes over (if it exists.)CS 307 Fundamentals of Computer ScienceJava Basics - Exceptions and File I/O6Attendance Question 1Is it possible for the following method to result in an exception?// pre: word != nullpublic static void printLength(String word){String output = "Word length is " + word.length();St titl(tt)System.out.println( output );}A. YesA. YesB. NoCS 307 Fundamentals of Computer ScienceJava Basics - Exceptions and File I/O7Unchecked Exceptions8 Exceptions in Java fall into two different categories– checked (other than Runtime) and unchecked (Runtime)8unchecked exceptions are completely preventableand u c ec ed e cept o s a eco p ete y p e e tab eadshould never occur. – They are caused by logic errors, created by us, the programmers.8Descendents of the RuntimeException class8Descendents of the RuntimeException class8 Examples: ArrayIndexOutOfBoundsException, NullPointerException, ArithmeticException8 There does not needto be special error handling code– just regular error prevention code8 If error handling code was required programs would be e o a d g code as equ ed p og a s ou d beunwieldy because so many Java statements have the possibility of generating or causing an unchecked ExceptionCS 307 Fundamentals of Computer ScienceJava Basics - Exceptions and File I/O8Checked Exceptions8"Ch k d ti t diti8"Checked exceptions represent conditions that, although exceptional, can reasonably be expected to occur and if they do occurbe expected to occur, and if they do occur must be dealt with in some way.[other than the program terminating ]"the program terminating.]– Java Programming Language third edition8Unchecked exceptions are due to aUnchecked exceptions are due to a programming logic error, our fault and preventable if coded correctly.py8Checked exceptions represent errors that are unpreventable by us!CS 307 Fundamentals of Computer ScienceJava Basics - Exceptions and File I/O9pyRequired Error Handling Code8If ll th d th t t8If you call a method that can generate a checked exception you must choose how to d l ith th t ibldeal with that possible error8For example one class for reading from files is the FileReader classpublic FileReader(StringfileName) throws FileNotFoundException8This constructor has the possibility of throwing a py gFileNotFoundException8FileNotFoundException is a checked exceptionCS 307 Fundamentals of Computer ScienceJava Basics - Exceptions and File I/O10Checked Exceptions in Code8If we have code that tries to build a FileReader we must deal with the possibility of the exceptionimport java.io.FileReader;public class Tester{public int countChars(String fileName){ FileReader r = new FileReader(fileName);int total = 0;while( r.ready() ){ r.read();total++;}}r.close();return total;} }8 The code contains a syntax error. "unreported exception java.io.FileNotFoundException; must be caught or declared }CS 307 Fundamentals of Computer ScienceJava Basics - Exceptions and File I/O11jp;gto be thrown."Handling Checked Exceptions8I th d th i lid th i8In the code on the previous slide there are in fact 4 statements that can generate checked exceptionsexceptions. – The FileReader constructorthe ready method–the ready method– the read method–the close method–the close method8To deal with the exceptions we can either state this method throws an Exception of thestate this method throws an Exception of the proper type or handle the exception within the method itselfCS 307 Fundamentals of Computer ScienceJava Basics - Exceptions and File I/O12Methods that throw Exceptions88It may be that we don't know how to deal with an error within the method that can generate it8In this case we will pass the buck to the method that called us8The keyword throws is used to indicate a ymethod has the possibility of generating an


View Full Document

UT CS 307 - Exceptions and File I/O

Documents in this Course
Midterm 2

Midterm 2

15 pages

Midterm 1

Midterm 1

15 pages

Syllabus

Syllabus

24 pages

s

s

8 pages

Midterm 1

Midterm 1

14 pages

Midterm 2

Midterm 2

14 pages

Recursion

Recursion

14 pages

Midterm 1

Midterm 1

16 pages

Load more
Download Exceptions and File I/O
Our administrator received your request to download this document. We will send you the file to your email shortly.
Loading Unlocking...
Login

Join to view Exceptions and File I/O and access 3M+ class-specific study document.

or
We will never post anything without your permission.
Don't have an account?
Sign Up

Join to view Exceptions and File I/O 2 2 and access 3M+ class-specific study document.

or

By creating an account you agree to our Privacy Policy and Terms Of Use

Already a member?