Title: CS 2
1CS 2
- Introduction to
- Object Oriented Programming
- Chapter 14
- Exceptions
2Chapter Goals
- To learn how to throw exceptions
- To be able to design your own exception classes
- To understand the difference between checked and
unchecked exceptions - To learn how to catch exceptions
- To know when and where to catch an exception
3Outdated Error Codes
- Traditional approach to error handling method
returns error code - Example JOptionPane.showInputDialog returns null
if user hits Cancel - Problem Calling method may forget to check for
error code - Problem Calling method may not know how to fix
error--then it needs to return an error code - Symptom Programming for successx.doSomething()
is replaced by programming for failure,constantly
anticipating problems that may occurif
(!x.doSomething()) return false
4Advantages of Javas Exception Handling
- Separates error handling code from the "regular"
code - Propagates exceptions automatically up the method
call stack when necessary - Allows grouping and differentiating among
exception types
5Exceptions
- Some knowledge of exceptions is required to use
Java successfully (IO) - Can be handled by a competent handler, not
necessarily the calling method - Throw an exception object to indicate failureif
(failure) XxxException e new
XxxException(. . .) throw e - More conciselyif (failure) throw new
XxxException(. . .)
6Exceptions
public class BankAccount public void
withdraw(double amount) if (amount
gt balance) throw new
IllegalArgumentException( "amount exceeds
balance") balance balance -
amount ...
7What exactly happens when an exception is
thrown?
- An exception object is created (on the heap)
- The current "context" is halted/aborted
- Execution starts in some error handling code
- Can be in current method
- Can be external to current method
- The error handling code has access to the
exception object which can be used to - Access a String message contained in the
exception - Determine what type of exception was thrown
- Print a stack trace
- Other cool stuff (like rethrow the exception,
increment a counter, etc.)
8Hierarchy of Exception Classes
9Syntax 14.1 Throwing an Exception
- throw exceptionObject
- Example
- throw new IllegalArgumentException()
- Purpose
- To throw an exception and transfer control to a
handler for this exception type
10Checked Exceptions
- Compiler requires you to be aware of
theexception - and actually provide code
concerning it - Generally used for errors that can happen even
in correct programs - IOException and its subclasses are checked
exceptions - Versus unchecked which are considered your
fault -) - The classification is not perfect. For example,
Integer.parseInt throws unchecked
NumberFormatException - Checked exceptions are subclasses of Exception
that are not subclasses of RuntimeException
(unchecked)
11Unchecked Exceptions
- Compiler does not require any code to deal with
or acknowledge the exceptions possibility - Generally used for problems that ultimately
could have been avoided by better programming - NullPointerException, ArrayIndexOutOfBoundsExcep
tion , ... are unchecked -- they are your fault
-) - Virtual machine errors (e.g. OutOfMemoryError)
are unchecked - As mentioned before, Integer.parseInt throws
unchecked NumberFormatException despite that it
seems it should be checked - All subclasses of RuntimeException are
unchecked RuntimeException itself is a subclass
of Exception
12What are some subclasses of class
RuntimeException?
- RuntimeException Examples
- ArithmeticException
- ClassCastException
- EmptyStackException
- IllegalArgumentException
- IndexOutOfBoundsException
- UnsupportedOperationException
- NegativeArraySizeException
- NoSuchElementException
- NullPointerException
So no special note must be made in headers of
methodsthrow these.
RuntimeExceptions do not have to be handled.
Program can be allowed to terminate.
13Checked Unchecked Exceptions
14Some methods common to all Exception objects
Object
Error
Exception
RuntimeException
15Exception Specifications
- BufferedReader.readLine() may throw IOException
(which is a checked exception) - Two ways to deal with this (and any checked
exception) - Tag calling method with throws
IOExceptionpublic class Coin public void
read(BufferedReader in) throws
IOException value Double.parseDouble(in.r
eadLine()) name in.readLine()
... - Provide a catch block in the method that calls
readLine()(more about this later)
16How do you know which methods throw exceptions?
17Check the API...
- readLine
- public readLine() throws IOException
- Read a line of text. A line is considered to be
terminated by any one of a line feed ('\n'), a
carriage return ('\r'), or a carriage return
followed immediately by a linefeed. - Returns
- A String containing the contents of the line,
not including any line- - termination characters, or null if the end of
the stream has been reached - Throws
- IOException - If an I/O error occurs
18Exception Specifications
- Need to tag caller of Coin.read() as well
- Stop at main or with handler (see below)
- Can have multiple exception typespublic void
read() throws IOException, ClassNotFoundExcept
ion - throws specifier not a sign of irresponsible
programming - Better to declare exception than to handle it
incompetently
19Syntax 14.2 Exception Specification
- accessSpecifier returnType methodName(paramType
paramName, . . .)throws ExceptionClass,
ExceptionClass . . . - Example
- public void read(BufferedReader in)
throws IOException - Purpose
- To indicate and basically warn user about the
checked exceptions that a method can throw - It is required by the compiler if a checked
exception can occur, and this method does not
catch that possible exception
20Designing Your Own Exception Types
- if (amount gt balance) throw new
InsufficientFundsException(. . .) - Make it an unchecked exception--programmer
could avoid it by calling getBalance first - Extend RuntimeException class
- Always write two constructors
- one with no parameters (default constructor)
- one with a String parameter
21Designing Your Own Exception Types
public class InsufficientFundsException
extends RuntimeException public
InsufficientFundsException()
public InsufficientFundsException(String
reasonMsg) super(reasonMsg)
Ask yourself, why does the default constructor
not require any code at all? Also, why do we
bother providing it dont we get it for free???
22Catching Exceptions
try BufferedReader in new
BufferedReader( new
InputStreamReader(System.in))
System.out.println("How old are you?")
String inputLine in.readLine() int age
Integer.parseInt(inputLine) age
System.out.println("Next year, you'll be "
age) catch (IOException exception)
System.out.println("Input/output error
exception) catch (NumberFormatException
exception) // unchecked, but can choose to
catch it System.out.println("Input was not
a number")
23Catching Exceptions
- Statements in try block are executed
- If no exceptions occur, catch clauses are skipped
- If exception occurs, execution jumps to the
matching catch clause, should it exist. - If exception of another type occurs, it is thrown
to the calling method - If main doesn't catch an exception, the program
terminates with a stack trace
24Syntax 14.3 General Try Block
- try statement statement ...
catch (ExceptionClass exceptionObject)
statement statement ... catch
(ExceptionClass exceptionObject) statement
statement ......
25- Example
- try System.out.println("What is your
name?") String name console.readLine()
System.out.println("Hello,"name "!")
catch (IOException exception)
exception.printStackTrace() System.exit(1)
- Purpose
- To execute one or more statements that may
generate exceptions. If an exception of a
particular type occurs, then stop executing those
statements and instead go to the matching catch
clause. If no exception occurs, then skip the
catch clauses.
26The finally Clause
- Exception terminates current method
- Danger Can skip over essential code
- Example BufferedReader in in new
BufferedReader( new
FileReader(filename)) purse.read(in)
in.close() - Must execute in.close() even if exception happens
- Use finally clause for code that must be executed
"no matter what" (exception occurs and is caught
or not caught, or no exception occurs)
27The finally Clause
- BufferedReader in null try in new
BufferedReader( new FileReader(filename))
purse.read(in) finally if (in !null)
in.close()
28The finally Clause
- Executed when try block comes to normal end
- Executed if a statement in try block throws an
exception, before exception is thrown out of try
block - Can also be combined with catch clauses
29Syntax 14.4 The finally Clause
- try statement statement ...
finally - statement statement ...
30- Example
- BufferedReader in null
- try
- in new BufferedReader( new
FileReader(filename)) purse.read(in) -
- finally
- if (in !null) in.close()
-
- Purpose
- To execute one or more statements that may
generate exceptions, and to execute the
statements in the finally clause whether or not
an exception occurs.
31Weird try/catch/finally example
- public class WeirdHandling
- public int whatValue ()
- try
- return 0
-
- catch (Exception e)
- return 1
-
- finally
- return 2
-
- // whatValue()
- public static void main(String args)
- WeirdHandling weird new WeirdHandling()
- System.out.println(weird.whatValue())
-
What value do you think is printed?
32Tough example of exception propagation
- Suppose we have 3 methods
- method1 // calls method2
- method2 // calls method3
- method3, a.k.a. badBoy // attempts to open a
non-existent file causing an exception to be
thrown. - We would like method1 to deal with the exception
created while in badBoy(). - How do we make this scenario happen?
33Example of exception propagation
- public void method1()
- try method2()
-
- catch (Exception e)
- // do exception handling here
-
- // method1()
- public void method2() throws Exception
- badBoy()
- // method2()
- public void badBoy() throws Exception
- // assume this method causes the
- // exception to be thrown!
- openThisFile("FileThatDoesntExist.txt")
- // badBoy
Bam!
34A Complete Example
- Program
- reads coin descriptions from file
- adds coins to purse
- prints total
- What can go wrong?
- File might not exist
- File might have data in wrong format
- Who can detect the faults?
- main method of PurseTest interacts with user
- main method can report errors
- Other methods pass exceptions to caller
35Coin Reading Example
main Purse myPurse new Purse()
myPurse.readFile(name)
Bad file name
No data
Bad format
Bad name
36The read method of the Coin class
- Distinguishes between expected and unexpected end
of file - public boolean read(BufferedReader in) throws
IOException - String input in.readLine() if (input
null) // normal end of file return false
value Double.parseDouble(input) // may
throw unchecked NumberFormatException name
in.readLine() if (name null) //
unexpected end of file throw new
EOFException("Coin name expected") return
true
Expected file format a line with a double and
then a line with a coin name (String)
37The read method of the Purse class
- Unconcerned with exceptions
- Just passes them to caller, does not catch them
- public void read(BufferedReader in) throws
IOException - boolean done false while
(!done) Coin c new Coin() if
(c.read(in)) add(c) else - done true
38The readFile method of the Purse class
- finally clause closes files if exception happens
- public void readFile(String filename)
throws IOException -
- BufferedReader in null try in new
BufferedReader( new FileReader(filename))
read(in) finally //
check if it even successfully opened if (in
! null) in.close() -
39User interaction in main
- If a reading exception occurs, user can specify
another file name - Initial setup shown below, while loop to do
reading found on following slides -
- // flag to help determine when to stop
- boolean done false
-
- String filename JOptionPane.showInputDialog(
- "Enter file name")
40 while (!done) // loops to prompt user until a
file is // successfully read or
user cancels try Purse
myPurse new Purse()
myPurse.readFile(filename)
System.out.println("total"
myPurse.getTotal()) done
true // read successfully so stop
catch (IOException exception)
System.out.println("Input/output error "
exception)
catch (NumberFormatException exception)
// error in file format
exception.printStackTrace()
41 if (!done) // not successful yet, but
exceptions were caught, // so continue and
let user have another chance filename
JOptionPane.showInputDialog(
"Try another file") if
(filename null) // if user hit cancel
done true // user wants to stop
// end if // end if // end of while
42Scenario
- PurseTest.main calls Purse.readFile
- Purse.readFile calls Purse.read
- Purse.read calls Coin.read
- Coin.read throws an EOFException
- Coin.read has no handler for the exception and
terminates immediately. - Purse.read has no handler for the exception and
terminates immediately - Purse.readFile has no handler for the exception
and terminates immediately after executing the
finally clause and closing the file. - PurseTest.main has a handler for an IOException ,
a superclass of EOFException. That handler prints
a message to the user. Afterwards, the user is
given another chance to enter a file name. Note
that the statement printing the purse total has
been skipped.
43File PurseTest.java
- 1 import javax.swing.JOptionPane
- 2 import java.io.IOException
- 3
- 4 /
- 5 This program prompts the user to enter a
file name - 6 with coin values. A purse object is filled
with - 7 the coins specified in the file. In case of
an exception, - 8 the user can choose another file.
- 9 /
- 10 public class PurseTest
- 11
- 12 public static void main(String args)
- 13
- 14 boolean done false
- 15 String filename
- 16 JOptionPane.showInputDialog("Enter
file name") - 17
44- 18 while (!done)
- 19
- 20 try
- 21
- 22 Purse myPurse new Purse()
- 23 myPurse.readFile(filename)
- 24 System.out.println("total"
myPurse.getTotal()) - 25 done true // file read was
success, so want to stop - 26
- 27 catch (IOException exception)
- 28
- 29 System.out.println("Input/output
error " exception) - 30
- 31 catch (NumberFormatException
exception) - 32
- 33 exception.printStackTrace()
- 34
- 35
45- 36 if (!done)
- 37 filename JOptionPane.showInputD
ialog( - 38 "Try another file")
- if (filename null)
- done true // user wants to
stop -
-
- // end of while
- System.exit(0)
- // end of main()
- // end of PurseTest class
46File Purse.java
- 1 import java.io.BufferedReader
- 2 import java.io.FileReader
- 3 import java.io.IOException
- 4
- 5 /
- 6 A purse computes the total of a collection
of coins. - 7 /
- 8 public class Purse
- 9
- 10 /
- 11 Constructs an empty purse.
- 12 /
- 13 public Purse()
- 14
- 15 total 0
- 16
- 17
47- 18 /
- 19 Read a file with coin descriptions and
adds the coins - 20 to the purse.
- 21 _at_param filename the name of the file
- 22 /
- 23 public void readFile(String filename)
- 24 throws IOException
- 25
- 26 BufferedReader in null
- 27 try
- 28
- 29 in new BufferedReader(new
FileReader(filename)) - 30 read(in)
- 31
- 32 finally
- 33
- 34 if (in ! null) in.close()
- 35
- 36
48- 38 /
- 39 Read a file with coin descriptions and
adds the coins - 40 to the purse.
- 41 _at_param in the buffered reader for
reading the input - 42 /
- 43 public void read(BufferedReader in)
- 44 throws IOException
- 45
- 46 boolean done false
- 47 while (!done)
- 48
- 49 Coin c new Coin()
- 50 if (c.read(in))
- 51 add(c)
- 52 else
- 53 done true
- 54
- 55
- 56
49- /
- 58 Add a coin to the purse.
- 59 _at_param aCoin the coin to add
- 60 /
- 61 public void add(Coin aCoin)
- 62
- 63 total total aCoin.getValue()
- 64
- 65
- 66 /
- 67 Get the total value of the coins in the
purse. - 68 _at_return the sum of all coin values
- 69 /
- 70 public double getTotal()
- 71
- 72 return total
- 73
- 74
- 75 private double total
50File Coin.java
- 1 import java.io.BufferedReader
- 2 import java.io.EOFException
- 3 import java.io.IOException
- 4
- 5 /
- 6 A coin with a monetary value.
- 7 /
- 8 public class Coin
- 9
- 10 private double value
- 11 private String name
- 12 /
- 13 Constructs a default coin.
- 14 Use the read method to fill in the value
and name. - 15 /
- 16 public Coin()
- 17 value 0
- name ""
-
51- 20 /
- 21 Constructs a coin.
- 22 _at_param aValue the monetary value of the
coin. - 23 _at_param aName the name of the coin
- /
- 25 public Coin(double aValue, String aName)
- 26
- 27 value aValue
- 28 name aName
- 29
- 30
- 31 /
- 32 Reads a coin value and name.
- 33 _at_param in the reader
- 34 _at_return true if the data was read,
- 35 false if the end of the stream was
reached - 36 /
52- 37 public boolean read(BufferedReader in)
- 38 throws
IOException - 39
- 40 String input in.readLine()
- 41 if (input null) return false
- 42 value Double.parseDouble(input)
- 43 name in.readLine()
- 44 if (name null)
- 45 throw new EOFException("Coin name
expected") - 46 return true
- 47
- 48
- 49 /
- 50 Gets the coin value.
- 51 _at_return the value
- 52 /
- 53 public double getValue()
- 54
- 55 return value
53- 57
- 58 /
- 59 Gets the coin name.
- 60 _at_return the name
- 61 /
- 62 public String getName()
- 63
- 64 return name
- 65
- 66
54Summary you should now
- Know how to throw exceptions
- Be able to design your own exception classes
- Understand the difference between checked and
unchecked exceptions - Know how to catch exceptions
- Know when and where to catch an exception
55Questions?