Unformatted text preview:

Topic 4 Exceptions and File I/OWhen Good Programs Go BadHow to Handle Errors?ExceptionsPartial Exceptions HierarchyCreating ExceptionsAttendance Question 1Unchecked ExceptionsChecked ExceptionsRequired Error Handling CodeChecked Exceptions in CodeHandling Checked ExceptionsMethods that throw ExceptionsUsing the throws KeywordUsing try-catch BlocksSample try and catch BlocksMechanics of try and catchGacky try catch BlockMore try catch MechanicsWhat Happens When Exceptions OccurCounting Chars AgainThrowing Exceptions YourselfAttendance Question 2Attendance Question 3Error Handling, Error Handling Everywhere!Error PreventionSlide 27File Input and OutputStreams?StreamsLots of StreamsWorking with Files in JavaThe Scanner classScanner and Keyboard InputHooking a Scanner up to a FileWriting to a FileReading From a Web PageCS 307 Fundamentals of Computer ScienceJava Basics - Exceptions and File I/O1Topic 4 Exceptions and File I/O"A 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."- 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/O2When Good Programs Go BadA variety of errors can occur when a program is running. For example:–(real) user input error. bad url–device errors. remote server unavailable–physical limitations. full disk–code errors. interact with code that does not fulfill its contact (pre and post conditions)when an error occurs–return 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/O3How 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/O4Exceptions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/O5Partial Exceptions HierarchyThrowableIOException RuntimeExceptionEOFException FileNotFoundExceptionArithmeticExceptionNullPointerExceptionIndexOutofBoundsExceptionIllegalArgumentExceptionAnd many, many, many more…ErrorExceptionCS 307 Fundamentals of Computer ScienceJava Basics - Exceptions and File I/O6Creating 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 with the exception–the normal flow of the program stops and error handling code takes over (if it exists.)CS 307 Fundamentals of Computer ScienceJava Basics - Exceptions and File I/O7Attendance 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(); System.out.println( output );}A. YesB. NoCS 307 Fundamentals of Computer ScienceJava Basics - Exceptions and File I/O8Unchecked ExceptionsExceptions in Java fall into two different categories–checked (other than Runtime) and unchecked (Runtime)unchecked exceptions are completely preventable and should never occur. –They are caused by logic errors, created by us, the programmers.Descendents of the RuntimeException classExamples: ArrayIndexOutOfBoundsException, NullPointerException, ArithmeticExceptionThere does not need to be special error handling code–just regular error prevention codeIf error handling code was required programs would be unwieldy 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/O9Checked Exceptions"Checked exceptions represent conditions that, although exceptional, can reasonably be expected to occur, and if they do occur must be dealt with in some way.[other than the program terminating.]"–Java Programming Language third editionUnchecked exceptions are due to a programming logic error, our fault and preventable if coded correctly.Checked exceptions represent errors that are unpreventable by us!CS 307 Fundamentals of Computer ScienceJava Basics - Exceptions and File I/O10Required Error Handling CodeIf you call a method that can generate a checked exception you must choose how to deal with that possible errorFor example one class for reading from files is the FileReader classpublic FileReader(String fileName) throws FileNotFoundExceptionThis constructor has the possibility of throwing a FileNotFoundExceptionFileNotFoundException is a checked exceptionCS 307 Fundamentals of Computer ScienceJava Basics - Exceptions and File I/O11Checked Exceptions in CodeIf we have code that tries to build a FileReader we must deal with the possibility of the exceptionThe code contains a syntax error. "unreported exception java.io.FileNotFoundException; must be caught or declared to be thrown."import 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;} }CS 307 Fundamentals of Computer ScienceJava Basics - Exceptions and File I/O12Handling Checked ExceptionsIn the code on the previous slide there are in fact 4 statements that can generate checked exceptions. –The FileReader constructor–the ready method–the read method–the close methodTo deal with the exceptions we can either state 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/O13Methods that throw ExceptionsIt may be that we don't know how to deal with an error within the


View Full Document

UT CS 307 - Topic 4 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 Topic 4 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 Topic 4 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 Topic 4 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?