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 BadAitf hA 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)when an error occurs–return to safe state save work exit gracefullyreturn to safe state, save work, exit gracefullyerror 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?It is possible to detect and handle errors of various types.Problem: 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.A tradeoff between ensuring correct behavior under all possible circumstances and clarity of the codeCS 307 Fundamentals of Computer ScienceJava Basics - Exceptions and File I/O3ExceptionsMany 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 ExceptionsAs 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 Exceptions Exceptions in Java fall into two different categories– checked (other than Runtime) and unchecked (Runtime)unchecked 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.Descendents of the RuntimeException classDescendents of the RuntimeException class Examples: ArrayIndexOutOfBoundsException, NullPointerException, ArithmeticException There does not needto be special error handling code– just regular error prevention code 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 Exceptions"Ch k d ti t diti"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 editionUnchecked exceptions are due to aUnchecked exceptions are due to a programming logic error, our fault and preventable if coded correctly.pyChecked exceptions represent errors that are unpreventable by us!CS 307 Fundamentals of Computer ScienceJava Basics - Exceptions and File I/O9pyRequired Error Handling CodeIf ll th d th t tIf you call a method that can generate a checked exception you must choose how to d l ith th t ibldeal with that possible errorFor example one class for reading from files is the FileReader classpublic FileReader(StringfileName) throws FileNotFoundExceptionThis constructor has the possibility of throwing a py gFileNotFoundExceptionFileNotFoundException is a checked exceptionCS 307 Fundamentals of Computer ScienceJava Basics - Exceptions and File I/O10Checked Exceptions in CodeIf 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;} } 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 ExceptionsI th d th i lid th iIn 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 methodTo 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 ExceptionsIt may be that we don't know how to deal with an error within the method that can generate itIn this case we will pass the buck to the method that called usThe keyword throws


View Full Document

UT CS 307 - Lecture Slides

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 Lecture Slides
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 Lecture Slides 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 Lecture Slides 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?