Java Exception Handling Handling errors using Java’s exception handling mechanism.
OO Design and Programming II Chapter 17 Exception Handling
description
Transcript of OO Design and Programming II Chapter 17 Exception Handling
04/22/23
CS262
1
OO Design and OO Design and Programming II Programming II
Chapter 17Chapter 17Exception Exception HandlingHandling
04/22/232CS262
What is an Exception?What is an Exception? An exception is an event that occurs during the execution of
a program that disrupts the normal flow of instructions. When an error occurs within a method, the method creates
an exception object and hands it off to the runtime system The exception object contains information about the error,
including its type and state of the program when the error occurred.
Creating an exception object and handing it to the runtime system is called throwing an exception.
04/22/233CS262
main
Method that has an exception handler
Method without an exception handler
Method where exception occurred
The call stack
Method call
Method call
Method call
04/22/234CS262
main
Method that has an exception handler
Method without an exception handler
Method where error occurred Looking for
appropriate handler
Looking for appropriate handler
Throws exception
not caught
Catches exception
When an error occurs, the runtime system searches the call stack for an appropriate error handler
“ducks”
04/22/235CS262
Catch and SpecifyCatch and Specify Catch: a method can catch an
exception by providing an exception handler for that type of exception.
Specify: If a method chooses not to catch an exception, the method must specify that it can throw that exception.
04/22/236CS262
Two kinds of ExceptionsTwo kinds of Exceptions1.1. Runtime exceptionsRuntime exceptions
Arithmetic exceptionsArithmetic exceptions Pointer exceptions (accessing an Pointer exceptions (accessing an
object’s members via null reference)object’s members via null reference) Indexing exceptions (accessing array Indexing exceptions (accessing array
element)element)2.2. Non-runtime exception (also called Non-runtime exception (also called
checked exceptionchecked exception)) I/OI/O
04/22/237CS262
The Throwable CLassThe Throwable CLass
Throwable
Object
Error Exception
IOException
RuntimeException
MyExceptionunchecked
unchecked
checked
04/22/238CS262
Checked or Unchecked Checked or Unchecked ExceptionsExceptions
Unchecked Exceptions
04/22/239CS262
Runtime exceptionsRuntime exceptions Arithmetic exceptionsArithmetic exceptions See example: BJ_Exceptions/Exc0.javaSee example: BJ_Exceptions/Exc0.java
compiled but runtime errorcompiled but runtime error BJ_Exceptions/Exc1.javaBJ_Exceptions/Exc1.java Compare Exc0 and Exc1 when the Compare Exc0 and Exc1 when the
exception occursexception occurs See the stack trace when exception See the stack trace when exception
occursoccurs
04/22/2310CS262
Writing your own Writing your own HandlerHandler
Examples Exc0.java and Exc1.java use Examples Exc0.java and Exc1.java use the Java run-time environment the Java run-time environment exception handlersexception handlers
Write your own handlers with Write your own handlers with trytry catchcatch
Examples:Examples: BJ_Exceptions/Exc2.javaBJ_Exceptions/Exc2.java BJ_Exceptions/HandleErrorA.javaBJ_Exceptions/HandleErrorA.java BJ_Exceptions/HandleErrorB.javaBJ_Exceptions/HandleErrorB.java
04/22/2311CS262
Not just one catchNot just one catch Multiple catchesMultiple catches are allowed in a try- are allowed in a try-
catch statementcatch statement Examples:Examples:
BJ_Exceptions/Multicatch.javaBJ_Exceptions/Multicatch.java Caution: Exception subclasses must Caution: Exception subclasses must
precede their exception superclasses. precede their exception superclasses. Otherwise the subclasses are not reachableOtherwise the subclasses are not reachable
Example: Example: BJ_Exceptions/SuperSubCatch.javaBJ_Exceptions/SuperSubCatch.java
04/22/2312CS262
Nested try clausesNested try clauses A try clause can be nested in another try.A try clause can be nested in another try. Each time a try clause is entered, the context of Each time a try clause is entered, the context of
that exception is pushed on the stack.that exception is pushed on the stack. If an inner try clause does not have a catch If an inner try clause does not have a catch
handler for a particular exception, the stack is handler for a particular exception, the stack is unwound and the next try clause's catch handlers unwound and the next try clause's catch handlers are inspected for a match. This continues until are inspected for a match. This continues until one of the catch clauses succeeds, or until all of one of the catch clauses succeeds, or until all of the nested try statements are exhausted.the nested try statements are exhausted.
If no catch clause matches, then the Java run-time If no catch clause matches, then the Java run-time environment system will handle the exception.environment system will handle the exception.
Example: BJ_Exception/NestTry.javaExample: BJ_Exception/NestTry.java
04/22/2313CS262
You can be a pitcher tooYou can be a pitcher too So far you have been catching exceptionsSo far you have been catching exceptions You can throw exceptions tooYou can throw exceptions too General form of General form of throw:throw:
throw ThrowableInstancethrow ThrowableInstance Primitive types, non-Throwable classes e.g. Primitive types, non-Throwable classes e.g.
String and Object cannot be used as String and Object cannot be used as exceptionsexceptions
Two ways to obtain a Throwable object:Two ways to obtain a Throwable object: using a parameter in a catch phraseusing a parameter in a catch phrase creating a Throwable object with the creating a Throwable object with the newnew
operatoroperator
04/22/2314CS262
Method must declare a Method must declare a throwthrow
If method does not catch, don’t just throw If method does not catch, don’t just throw but you need to but you need to declaredeclare up front for up front for intention intention to throwto throw
General form of method declaration that General form of method declaration that includes a includes a throwsthrows clause clause
type method-name(parameter-list) type method-name(parameter-list) throws throws exception-listexception-list
{{// body of method// body of method
}}
04/22/2315CS262
ExamplesExamples BJ_Throw/BJ_Throw/
IncorrectThrowsDemo.javaIncorrectThrowsDemo.java BJ_Throw/CorrectThrowsDemo.javaBJ_Throw/CorrectThrowsDemo.java BJ_Throw/ThrowDemo.javaBJ_Throw/ThrowDemo.java
04/22/2316CS262
try-catch--finallytry-catch--finallytry { Java statements} catch (ExceptionType e1) {//exception
Java Statements //handler} catch (ExceptionType e2) {
Java Statements} finally { // optional
Java Statements // If present, // always
executes// close files
// cleanup}
04/22/2317CS262
LabLab To determine the number of To determine the number of
characters, words, and lines in a filecharacters, words, and lines in a file Use FileReader to read a text fileUse FileReader to read a text file Use a simple finite state machine to Use a simple finite state machine to
count the number of words or linescount the number of words or lines
04/22/2318CS262
FileReaderFileReaderTo construct a FileReader, use the To construct a FileReader, use the
following constructors:following constructors:public FileReader(String filename)public FileReader(String filename)public FileReader(File file)public FileReader(File file)Ref: Ref:
http://java.sun.com/j2se/1.5.0/docs/api/java/io/FileReadehttp://java.sun.com/j2se/1.5.0/docs/api/java/io/FileReader.htmlr.html
A A java.io.FileNotFoundExceptionjava.io.FileNotFoundException would would occur if you attempt to create a occur if you attempt to create a FileReaderFileReader with a nonexistent file. with a nonexistent file.
04/22/2319CS262
How to read with How to read with FileReaderFileReader
// Create an input stream// Create an input stream input = new FileReader("temp.txt");input = new FileReader("temp.txt");
int code;int code; /* Repeatedly read a character and /* Repeatedly read a character and
display it on the console*/display it on the console*/ while ((code = input.read()) != -1)while ((code = input.read()) != -1) System.out.print((char)code);System.out.print((char)code);
04/22/2320CS262
// To catch I/O exceptions try { // Create an input stream // Repeatedly read a character and display it on the console } catch (FileNotFoundException ex) { System.out.println("File temp.txt does not exist"); } catch (IOException ex) { ex.printStackTrace(); } finally { try { input.close(); // Close the stream } catch (IOException ex) { ex.printStackTrace(); } }
04/22/2321CS262
FSM to count number of FSM to count number of lineslines
StateState Input Input char readchar read
ActionAction New New StateState
newLinenewLine ‘‘\n’\n’ lineCount +lineCount +++
newLinenewLine
newLinenewLine Not ‘\n’Not ‘\n’ nonenone !newLine!newLine
!newLine!newLine ‘‘\n’\n’ lineCount +lineCount +++
newLinenewLine
!newLine!newLine Not ‘\n’Not ‘\n’ nonenone !newLine!newLine
04/22/2322CS262
FSM to count wordsFSM to count wordsStateState Input char Input char
readreadActionAction New StateNew State
newWordnewWord None of WS None of WS characterscharacters
wordCountwordCount++++
notNewWornotNewWordd
newWordnewWord WS WS charactercharacter
nonenone newWordnewWord
notNewWornotNewWordd
Any WS Any WS charactercharacter
nonenone newWordnewWord
notNewWornotNewWordd
Non-WS Non-WS charactercharacter
nonenone notNewWornotNewWordd
WS are white space characters: ‘’, ‘\t’, or ‘\n’
04/22/23
CS262
23
checked checked exceptionsexceptionsSource Code Review and DemoSource Code Review and Demo
ListOfNumbers0.javaListOfNumbers0.javanew FileWriter("OutFile.txt") // Note new FileWriter("OutFile.txt") // Note
thisthisBut in But in
http://java.sun.com/j2se/1.5.0/docshttp://java.sun.com/j2se/1.5.0/docs/api//api/
FileWriter throws an exceptionFileWriter throws an exceptionpublic public FileWriterFileWriter((StringString fileName) fileName)
throws throws IOExceptionIOException
04/22/2324CS262
Exercise 5.1Exercise 5.1 Go to directory “Ex5.1 Checked Go to directory “Ex5.1 Checked
Exceptions”Exceptions” 1. Down load and compile 1. Down load and compile
ListOfNumers0.java as is.ListOfNumers0.java as is. 2. Study the changes in 2. Study the changes in
ListOfNumbers1.java and compile.ListOfNumbers1.java and compile. 3. Study the changes in 3. Study the changes in
ListOFNumbers2.java and compileListOFNumbers2.java and compile
04/22/2325CS262
try-catch--finallytry-catch--finallytry { Java statements} catch (ExceptionType e1) {//exception
Java Statements //handler} catch (ExceptionType e2) {
Java Statements} finally { // optional
Java Statements // If present, // always
executes// close files
// cleanup}
04/22/2326CS262
An ExampleAn Examplepublic void writeList() { PrintWriter out = null; try { System.out.println("Entering try statement"); out = new PrintWriter(new FileWriter("OutFile.txt")); for (int i = 0; i < size; i++) out.println("i + " = " + vector.elementAt(i)); } catch (ArrayIndexOutOfBoundsException e) { System.err.println("Caught ArrayIndexOutOfBoundsException:" +
e.getMessage()); } catch (IOException e) { System.err.println("Caught IOException: " + e.getMessage()); } finally { if (out != null) { System.out.println("Closing PrintWriter"); out.close(); } else { System.out.println("PrintWriter not open"); } }}
04/22/23
CS262
27
Source Code Source Code Review and Review and
DemoDemoDirectory “Ex5.2 Checked Directory “Ex5.2 Checked Exceptions”Exceptions”
ListOfNumbers.javaListOfNumbers.javaListOfNumbersTest.javaListOfNumbersTest.java
04/22/2328CS262
Exercise 5.2Exercise 5.21.1. Down load and run Down load and run
ListOfNumersTest.java as is.ListOfNumersTest.java as is.2.2. Change outFile.txt to read-only and Change outFile.txt to read-only and
run it againrun it again3.3. Change outFile.txt back to r/wChange outFile.txt back to r/w4.4. Change “i<size” to (i<=size) in Change “i<size” to (i<=size) in
ListOfNumbers.javaListOfNumbers.java5.5. Compile and run againCompile and run again6.6. Change the program backChange the program back
04/22/2329CS262
throwthrow We have looked at catching exceptions We have looked at catching exceptions
thrown by the Java Runtime systemthrown by the Java Runtime system Your program may also throw an Your program may also throw an
exceptionexception throw throw ThrowableInstance;ThrowableInstance; ThrowableInstance ThrowableInstance is an object of type is an object of type
ThrowableThrowable or a subclass of or a subclass of ThrowableThrowable
04/22/2330CS262
Exceptions Thrown by a Method
public Object pop() throws EmptyStackException { Object obj;
if (size == 0) throw new EmptyStackException(); obj = objectAt(size - 1); setObjectAt(size - 1, null); size--; return obj;}
*The EmptyStackException class is defined in the java.util package.
04/22/2331CS262
The Throwable CLassThe Throwable CLass
Throwable
Object
Error Exception
IOException
RuntimeException
MyExceptionunchecked
unchecked
04/22/2332CS262
What can you throw?What can you throw? ErrorError deals with internal errors and deals with internal errors and
resource exhaustion resource exhaustion Not much you can do if it occursNot much you can do if it occurs You should not throw a object of this typeYou should not throw a object of this type
ExceptionException Hierarchy Hierarchy Focus on ExceptionFocus on Exception
Runtime exception is due to a programming Runtime exception is due to a programming errorerror
I/O exceptions may occur to a good programI/O exceptions may occur to a good program
04/22/2333CS262
ExamplesExamples RuntimeExceptionsRuntimeExceptions
A bad castA bad cast An out-of-bounds array accessAn out-of-bounds array access A null pointer accessA null pointer access
Non RuntimeExceptions:Non RuntimeExceptions: Trying to read past the end of a fileTrying to read past the end of a file Trying to open a malformed URLTrying to open a malformed URL Trying to find a class object for a string Trying to find a class object for a string
that does not denote an existing classthat does not denote an existing class
04/22/2334CS262
Where do you advertise Where do you advertise your method may throw?your method may throw?
In the header of the methodIn the header of the method For example: readLine of BufferedReaderFor example: readLine of BufferedReaderpublic public StringString readLinereadLine() throws () throws
IOExceptionIOExceptionhttp://java.sun.com/j2se/1.4.2/docs/api/java/io/BufferedReader.html#BufferedReader(java.io.Readehttp://java.sun.com/j2se/1.4.2/docs/api/java/io/BufferedReader.html#BufferedReader(java.io.Readerr
))
Returns a StringReturns a String May also throw an IOExceptionMay also throw an IOException If such exception occurs, runtime system will If such exception occurs, runtime system will
search for an exception handler.search for an exception handler.
04/22/2335CS262
To Advertise a throw or To Advertise a throw or NotNot
You don’t have to advertise every possible throwable You don’t have to advertise every possible throwable objectobject
Then when and what you have to advertise?Then when and what you have to advertise? An exception is thrown in 4 situations:An exception is thrown in 4 situations:
1.1. You call a method that throws a checked exception, You call a method that throws a checked exception, for example, the readLine method of the for example, the readLine method of the BuffredReader classBuffredReader class
2.2. You detect an fault and throw a checked exception You detect an fault and throw a checked exception with the throw statementwith the throw statement
3.3. You make a programming error, such as array[-1] = You make a programming error, such as array[-1] = 0 and that gives rise to an unchecked exception such 0 and that gives rise to an unchecked exception such as ArrayIndexOutOfBoundsExceptionas ArrayIndexOutOfBoundsException
4.4. An internal error occurs in the virtual machine or An internal error occurs in the virtual machine or runtime libraryruntime library
04/22/2336CS262
To Advertise a throw or To Advertise a throw or NotNot
For cases 1 and 2, you must tell the For cases 1 and 2, you must tell the programmers who will use your method that programmers who will use your method that there is the possibility of an exceptionthere is the possibility of an exception Why? Any method that throws an exception may Why? Any method that throws an exception may
terminate the threadterminate the thread For cases 3 and 4, you should not and need For cases 3 and 4, you should not and need
not advertise not advertise Why? Why? You should fix the unchecked runtime exception You should fix the unchecked runtime exception
instead of advertising its possibility. It is instead of advertising its possibility. It is completely under your controlcompletely under your control
You cannot fix internal Java errorsYou cannot fix internal Java errors
04/22/23
CS262
37
Source Code Review and DemoSource Code Review and DemoBJ_ExceptionInPackage\BJ_ExceptionInPackage\
ExceptionDemo.javaExceptionDemo.java
Exercise .3: download and run Exercise .3: download and run ExceptionDemo.javaExceptionDemo.java
04/22/2338CS262
Why Exceptions?Why Exceptions? Separating Separating error handlingerror handling code from code from regular regular
code.code. Propagating errors up the call stack Propagating errors up the call stack
towards the callerstowards the callers Grouping and differentiating error Grouping and differentiating error
messages and typesmessages and types
04/22/2339CS262
Advantage 1 – Separating Advantage 1 – Separating Error-Handling code from Error-Handling code from
Regular CodeRegular CodereadFile { try { open the file; determine its size; allocate that much memory; read the file into memory; close the file; } catch (fileOpenFailed) { doSomething; } catch (sizeDeterminationFailed) { doSomething; } catch (memoryAllocationFailed) { doSomething; } catch (readFailed) { doSomething; } catch (fileCloseFailed) { doSomething; }}
04/22/2340CS262
Advantage 2 – Propagating Advantage 2 – Propagating Errors Errors
Up the Call StackUp the Call Stackmethod1 { // Only I am interested in errors try { call method2; } catch (Exception e) { doErrorProcessing; }}method2 throws Exception { // ‘throws’needed // to duck call method3;}method3 throws Exception { call readFile;}
04/22/2341CS262
Advantage 3Advantage 3
Throwable
Object
Error Exception
IOException
RuntimeException
MyException
04/22/2342CS262
Exercise 5.4Exercise 5.4 What are the exceptions you see in What are the exceptions you see in
Assignment #4?Assignment #4? No command line argumentsNo command line arguments Cannot open input filesCannot open input files Empty employee data fileEmpty employee data file Data format (syntax) errorsData format (syntax) errors Data semantic errors (sup does not Data semantic errors (sup does not
exist)exist) Table overflow Table overflow