Exception Handling
Chapter 9
JAVA: An Introduction to Problem Solving & Programming, 7th Ed. By Walter Savitch
ISBN 0133862119 © 2015 Pearson Education, Inc., Upper Saddle River, NJ. All Rights Reserved
Exceptions in Java
• Consider a program to assure us of a sufficient supply of milk
• View possible solution, listing 9.1
class GotMilk
Sample
screen
output
JAVA: An Introduction to Problem Solving & Programming, 7th Ed. By Walter Savitch
ISBN 0133862119 © 2015 Pearson Education, Inc., Upper Saddle River, NJ. All Rights Reserved
Exceptions in Java
• Now we revise the program to use exception-handling
• View new version, listing 9.2
class ExceptionDemo9_2 (9_2..9_4 same, see
comments)
Sample
screen Sample
output 1 screen
output 2
JAVA: An Introduction to Problem Solving & Programming, 7th Ed. By Walter Savitch
ISBN 0133862119 © 2015 Pearson Education, Inc., Upper Saddle River, NJ. All Rights Reserved
Exceptions in Java
• Note try block
• Contains code where something could possibly go wrong
• If it does go wrong, we throw an exception
• Note catch block
• When exception thrown, catch block begins execution
• Similar to method with parameter
• Parameter is the thrown object
• Parameter must “match” type of exception thrown
JAVA: An Introduction to Problem Solving & Programming, 7th Ed. By Walter Savitch
ISBN 0133862119 © 2015 Pearson Education, Inc., Upper Saddle River, NJ. All Rights Reserved
Exceptions in Java
• Note flow of control when no exception is thrown
• View demo with no exception, listing 9.3
class ExceptionDemo9_3
Sample
screen output with
no exception
JAVA: An Introduction to Problem Solving & Programming, 7th Ed. By Walter Savitch
ISBN 0133862119 © 2015 Pearson Education, Inc., Upper Saddle River, NJ. All Rights Reserved
Exceptions in Java
• Note flow of control when exception IS thrown
• View demo with exception, listing 9.4
class ExceptionDemo9_4
Sample
screen output when
exception is thrown
JAVA: An Introduction to Problem Solving & Programming, 7th Ed. By Walter Savitch
ISBN 0133862119 © 2015 Pearson Education, Inc., Upper Saddle River, NJ. All Rights Reserved
Exceptions in Java
• An exception is an object – use pre-existing one or define your own
• Signals the occurrence of unusual event during program execution
• It represents an exceptional circumstance
• Some coders will use it for input validation
• Throwing an exception – Code you write may need to throw an
exception
• Creating the exception object
• Then throwing it
• Can say a method throws a (checked) exception
• Handling the exception – Code you use or write may generate
Exceptions that you have to, or want to, handle
• Exceptions can be caught (catched)
• Should be caught at some point where the code can deal with the
exceptional circumstance
JAVA: An Introduction to Problem Solving & Programming, 7th Ed. By Walter Savitch
ISBN 0133862119 © 2015 Pearson Education, Inc., Upper Saddle River, NJ. All Rights Reserved
Predefined Exception Classes
• Java has predefined exception classes within Java Class Library
• Can place method invocation in try block
• Follow with catch block for this type of exception
• Example classes: note _______Exception pattern
• ClassNotFoundException – JVM not finding class file (class
path error)
• IOException – General I/O Exception
• ArithmeticException – General arithmetic exception, e.g.
division by zero
JAVA: An Introduction to Problem Solving & Programming, 7th Ed. By Walter Savitch
ISBN 0133862119 © 2015 Pearson Education, Inc., Upper Saddle River, NJ. All Rights Reserved
Predefined Exception Classes
• Example code
JAVA: An Introduction to Problem Solving & Programming, 7th Ed. By Walter Savitch
ISBN 0133862119 © 2015 Pearson Education, Inc., Upper Saddle River, NJ. All Rights Reserved
Defining Your Own Exception Classes
• Must be derived class of some predefined exception class
• Text uses classes derived from class Exception
• View sample class, listing 9.5
class DivideByZeroException
extends Exception
• View demo program, listing 9.6
class DivideByZeroDemo
• View demo (does integral division) – can use predefined
class ArithmeticDivByZeroDemo
JAVA: An Introduction to Problem Solving & Programming, 7th Ed. By Walter Savitch
ISBN 0133862119 © 2015 Pearson Education, Inc., Upper Saddle River, NJ. All Rights Reserved
Defining Your Own Exception Classes
• Different runs of the program
Sample
screen Sample
output 1Sample screen
output 3
screen
output 2
JAVA: An Introduction to Problem Solving & Programming, 7th Ed. By Walter Savitch
ISBN 0133862119 © 2015 Pearson Education, Inc., Upper Saddle River, NJ. All Rights Reserved
Defining Your Own Exception Classes
Guidelines
• Use the Exception as the base class
• Define at least two constructors
• Default, no parameter
• With String parameter
• Start constructor definition with call to constructor of base class,
using super
• Do not override inherited getMessage
• Note method getMessage defined in exception classes
• Returns string passed as argument to constructor
• If no actual parameter used, default message returned
• The type of an object is the name of the exception class
JAVA: An Introduction to Problem Solving & Programming, 7th Ed. By Walter Savitch
ISBN 0133862119 © 2015 Pearson Education, Inc., Upper Saddle River, NJ. All Rights Reserved
More About Exception Classes: Outline
• Declaring Exceptions (Passing the Buck)
• Kinds of Exceptions
• Errors
• Multiple Throws and Catches
• The finally Block
• Rethrowing an Exception
• Case Study: A Line-Oriented Calculator
JAVA: An Introduction to Problem Solving & Programming, 7th Ed. By Walter Savitch
ISBN 0133862119 © 2015 Pearson Education, Inc., Upper Saddle River, NJ. All Rights Reserved
Declaring Exceptions
• Consider method where code throws exception
• May want to handle immediately
• May want to delay until something else is done
• Method that does not catch an exception
• Notify programmers with throws clause
• Programmer then given responsibility to handle exception
JAVA: An Introduction to Problem Solving & Programming, 7th Ed. By Walter Savitch
ISBN 0133862119 © 2015 Pearson Education, Inc., Upper Saddle River, NJ. All Rights Reserved
Declaring Exceptions
• Note syntax for throws clause
• Note distinction
• Keyword throw used to throw exception
• Keyword throws used in method heading to declare an exception
JAVA: An Introduction to Problem Solving & Programming, 7th Ed. By Walter Savitch
ISBN 0133862119 © 2015 Pearson Education, Inc., Upper Saddle River, NJ. All Rights Reserved
Declaring Exceptions
• If a method throws exception and exception not caught inside the
method
• Method ends immediately after exception thrown
• i.e. regular order of execution
• A throws clause in overriding method
• Can declare fewer exceptions than declared
• But not more
• View program example, listing 9.7
class DoDivision
JAVA: An Introduction to Problem Solving & Programming, 7th Ed. By Walter Savitch
ISBN 0133862119 © 2015 Pearson Education, Inc., Upper Saddle River, NJ. All Rights Reserved
Kinds of Exceptions
• In most cases, exception is caught …
• In acatch block … or
• Be declared in throws clause
• But Java has exceptions you do not need to account for
• Categories of exceptions
• Checked exceptions
• Unchecked exceptions
JAVA: An Introduction to Problem Solving & Programming, 7th Ed. By Walter Savitch
ISBN 0133862119 © 2015 Pearson Education, Inc., Upper Saddle River, NJ. All Rights Reserved
Kinds of Exceptions
• Checked exception –Non-RuntimeException Exception
catch block
• Must be caught in
• Or declared in throws clause
• Unchecked exception – Descendent of RunTimeException
• Also called run-time
• Need not be caught in catch block or declared in throws
• Exceptions that coding problems exist, should be fixed
• When you know a problem exists it is better to simply report the exceptional situation
and let the programmer fix it versus requiring the programmer to work backwards from
the eventual side effects to the source
JAVA: An Introduction to Problem Solving & Programming, 7th Ed. By Walter Savitch
ISBN 0133862119 © 2015 Pearson Education, Inc., Upper Saddle River, NJ. All Rights Reserved
Kinds of Exceptions
• Checked Exceptions – most prior examples are Checked
• Examples why unchecked exceptions to are thrown
• Attempt to use array index out of bounds
• Division by zero
• Uncaught runtime exception terminates program execution
JAVA: An Introduction to Problem Solving & Programming, 7th Ed. By Walter Savitch
ISBN 0133862119 © 2015 Pearson Education, Inc., Upper Saddle River, NJ. All Rights Reserved
Kinds of Exceptions
• Figure 9.1 Hierarchy of the predefined exception classes
JAVA: An Introduction to Problem Solving & Programming, 7th Ed. By Walter Savitch
ISBN 0133862119 © 2015 Pearson Education, Inc., Upper Saddle River, NJ. All Rights Reserved
Errors
• An error is an object of class Error
• Similar to an unchecked exception
• Need not catch or declare in throws clause
• Object of class Error generated when abnormal conditions occur
• Errors are more or less beyond your control
• Require change of program to resolve
JAVA: An Introduction to Problem Solving & Programming, 7th Ed. By Walter Savitch
ISBN 0133862119 © 2015 Pearson Education, Inc., Upper Saddle River, NJ. All Rights Reserved
Multiple Throws and Catches
• A try block can throw any number of exceptions of different types
• Each catch block can catch exceptions of only one type
• Order of catch blocks matter
• View example program, listing 9.8
class TwoCatchesDemo
• View exception class used, listing 9.9
class NegativeNumberException
JAVA: An Introduction to Problem Solving & Programming, 7th Ed. By Walter Savitch
ISBN 0133862119 © 2015 Pearson Education, Inc., Upper Saddle River, NJ. All Rights Reserved
Multiple Throws and Catches
• Note multiple sample runs
Sample
screen
Sample
output 1
screen
output 2
Sample
screen
output 2
JAVA: An Introduction to Problem Solving & Programming, 7th Ed. By Walter Savitch
ISBN 0133862119 © 2015 Pearson Education, Inc., Upper Saddle River, NJ. All Rights Reserved
Multiple Throws and Catches
• Exceptions can deal with invalid user input
• To handle an exception thrown by a method
• It does not matter where in the method the throw occurs
• Use of throw statement be should be reserved for
cases where it is unavoidable
• Text suggests separate methods for throwing and
catching of exceptions
• Nested try-catch blocks rarely useful
JAVA: An Introduction to Problem Solving & Programming, 7th Ed. By Walter Savitch
ISBN 0133862119 © 2015 Pearson Education, Inc., Upper Saddle River, NJ. All Rights Reserved
The finally Block
• Possible to add a finally block after sequence of catch blocks
• Code in finally block executed
• Whether or not execution thrown
• Whether or not required catch exists
JAVA: An Introduction to Problem Solving & Programming, 7th Ed. By Walter Savitch
ISBN 0133862119 © 2015 Pearson Education, Inc., Upper Saddle River, NJ. All Rights Reserved
Rethrowing an Exception
• Legal to throw an exception within a catch block
• Possible to use contents of String parameter to throw same or
different type exception
JAVA: An Introduction to Problem Solving & Programming, 7th Ed. By Walter Savitch
ISBN 0133862119 © 2015 Pearson Education, Inc., Upper Saddle River, NJ. All Rights Reserved
Case Study
• A Line-Oriented Calculator
• Should do addition, subtraction, division, multiplication
• Will use line input/output
• User will enter
• Operation, space, number
• Calculator displays result
JAVA: An Introduction to Problem Solving & Programming, 7th Ed. By Walter Savitch
ISBN 0133862119 © 2015 Pearson Education, Inc., Upper Saddle River, NJ. All Rights Reserved
Case Study
• Proposed initial methods
• Method to reset value of result to zero
• Method to evaluate result of one operation
• Method doCalculation to perform series of operations
• Accessor method getResult: returns value of instance variable
result
• Mutator method setResults: sets value of instance variable
result
JAVA: An Introduction to Problem Solving & Programming, 7th Ed. By Walter Savitch
ISBN 0133862119 © 2015 Pearson Education, Inc., Upper Saddle River, NJ. All Rights Reserved
Case Study
• View exception class, listing 9.10
class UnknownOpException
• View first version of calculator, listing 9.11
class PreLimCalculator
Sample
screen
output
JAVA: An Introduction to Problem Solving & Programming, 7th Ed. By Walter Savitch
ISBN 0133862119 © 2015 Pearson Education, Inc., Upper Saddle River, NJ. All Rights Reserved
Case Study
• Final version adds exception handling
• Ways to handle unknown operator
• Catch exception in method evaluate
• Let evaluate throw exception, catch exception in doCalculation
• Let evaluate, doCalculation both throw exception, catch in main
• Latter option chosen
JAVA: An Introduction to Problem Solving & Programming, 7th Ed. By Walter Savitch
ISBN 0133862119 © 2015 Pearson Education, Inc., Upper Saddle River, NJ. All Rights Reserved
Case Study
• View final version, listing 9.12
class Calculator
Sample
screen
output
JAVA: An Introduction to Problem Solving & Programming, 7th Ed. By Walter Savitch
ISBN 0133862119 © 2015 Pearson Education, Inc., Upper Saddle River, NJ. All Rights Reserved