Title: Exceptions and Handling Them
1Exceptions and Handling Them
- In a program, some error conditions that come up
are recoverable, and can be handled. Some are
even sometimes expected. - We should be able to write code to handle these
and have our program still keep running (not
crash) - Roughly, in Java an exception is such a
recoverable condition. - On the other hand, an error is a condition
which you really ought not to try to recover
from. - Each time an exception occurs, Java sends to your
program an object, called an Exception object. - Java Language the exception is thrown to your
program from the exact point where it occurs
(normal execution ceases at that point). - You can add code to your program to receive the
exception event and respond to it (handle it)
doing something appropriate. - Usually, if you dont have code to handle an
exception, your program will crash if that
exception occurs.
2Troubled Code Exceptions Happen
3Exceptions Are Objects Exception Classes
- All Exception classes are in the package
java.lang. except the IOException family - Exception extends Throwable (which has method
void printStackTrace() ) - The classes Exception and Error are the children
of Throwable. - Child classes of Exception
- RuntimeException
- ArithmeticException (like integer-divide-by-zero)
- IndexOutOfBoundsException (children
ArrayIndexOutOfBoundsException,
StringIndexOutOfBoundsException). - NullPointerException
- IllegalArgumentException
- NumberFormatException
- NoSuchFieldException, NoSuchMethodException
- IOException (in java.io. )
- FileNotFoundException
- EOFException
- And many more!
- Children of Error and RuntimeException classes
are called unchecked exceptions . All others are
called checked exceptions. - When an exception occur, one of these objects is
sent to your code. It your code doesnt receive
and handle it, it will crash! Generally, you must
handle all checked exceptions in your code.
4Categories of Exceptions
java.lang.Throwable
java.lang.Exception
java.lang.Error
Serious Errors your program ought not try to
recover from
Checked Exceptions (all subclasses of Exception
except RuntimeException) ClassNotFoundException
DataFormatException IllegalAccessException Interru
ptedException IOException (childrenFileNotFoundE
xception MalformedURLException,
etc.) SQLException NoSuchFieldException NoSuchMeth
odException UserException and many more ?
java.lang.RuntimeException
Usually bugs in program! Dont have to recover
from Need to fix them ArithmeticException ArrayS
toreException ClassCastException IllegalArgumentEx
ception (child NumberFormatException) IndexOutOfB
oundsException (children for ArrayIndex and
for StringIndex) NullPointerException and many
more ?
5 Java try/catch/finally Structure
- Java provides mechanism to allow you to
anticipate and respond to Exceptions. - You can receive chosen exceptions and handle
them. - try
- exception suspicious code
-
-
- catch( SomeException e)
- occurrence
-
- finally // OPTIONAL often not
present
and catch blocks -
- Lets fix some of our troubled code
6Fixing the Null Pointer Exception
import java.awt. public class
Trouble1 public static void main(String
args) Point P new Point(2,3) int
xcoor (int) P.getX() System.out.println("xcoo
r " xcoor) try P null xcoor
(int) P.getX() System.out.println("xcoor "
xcoor) catch( Exception e) // could
catch NullPointerException here!! System.ou
t.println("Got Exception " e.toString())
e.printStackTrace() System.o
ut.println("But I will survive!") P new
Point(5,8) xcoor (int) P.getX() System.out
.println("xcoor " xcoor)
OUTPUT xcoor 2 Got Exception
java.lang.NullPointerException java.lang.NullPoint
erException at Trouble1.main(Trouble1.java
11) But I will survive! xcoor 5
7Fixing the Bad Number Typed In
import java.awt. import cs1.Keyboard public
class Trouble1 public static void
main(String args) boolean
validNum int inNum 0
System.out.println("Type in a Number below")
do
String input Keyboard.readString()
try inNum Integer.parseInt(input
) validNum true
catch( NumberFormatException e
)
validNum false
System.out.println("NUMBER FORMAT ERROR ILLEGAL
INPUT")
System.out.println("Type in a NUMBER below!! NOT
ANY OLD STRING!!!!")
while( !validNum)
System.out.println("Your number was "
inNum) A Run of this code Type in a
Number below Herbert NUMBER FORMAT ERROR
ILLEGAL INPUT Type in a NUMBER below!! NOT ANY
OLD STRING!!!! Mary NUMBER FORMAT ERROR ILLEGAL
INPUT Type in a NUMBER below!! NOT ANY OLD
STRING!!!! Delores Del Rio? NUMBER FORMAT ERROR
ILLEGAL INPUT Type in a NUMBER below!! NOT ANY
OLD STRING!!!! 256 Your number was 256
8Exception Considerations
- You must account for all checked exceptions (i.e.
non-Runtime Exceptions) in your code. - Either catch and handle them, or
- Announce that your method throws them
- Exceptions emanate from inside methods which
throw them. Methods should announce which checked
exceptions they throw with a throws-clause. This
is an expanded part of the method signature. - public int getAge() throws DataFormatException,
IOException - .
- Methods exit immediately (abnormally) when they
throw an exception (ignore return). - You may explicitly throw an exception with a
throw statement - You may create your own exceptions by extending
existing Exception classes - A try clause can have multiple catch clauses
more specific first but only one is executed
9Exceptions and Control Flow - Propagation
- Suppose method main( ) calls method A( ), and
method A( ) calls method B( ). - Suppose now that an exception E occurs inside a
line of B( )s code. - If this code is in a try/catch block for that
exception, then the exception E is handled
completely in B( ). B( ) then completes its work
and control passes back to A( ) (normal return
behavior). - If however, E occurred outside a try/catch block
in B( ), then the B( ) method is immediately
exited (like return) and control is passed back
into method A( ) at the line where A( ) called B(
). - Now things act as if the exception E had occurred
exactly at the position in A( ) where B( ) was
called. - If this position in A( ) is inside a try/catch
block for that exception, then E is handled
completely in A( ) and then A( ) completes its
work and control passes back to main( ) (normal
return behavior). - If however, this position in A( ) (where B was
called) is not in a try/catch block for this
exception, then method A( ) is immediately exited
(like return) and control is passed back into
method main( ) at the line where main( ) called
A( ). - Now things act as if the exception E had occurred
exactly at the position in main( ) where A() was
called. - If this position in main( ) is inside a try/catch
block for that exception, then E is handled
completely in main( ) and then main( ) completes
its work and eventually exits normally. - If however, this position in main( ) (where A was
called) is not in a try/catch block for this
exception, then method main( ) is immediately
exited (like crash-on-the-spot) and control is
passed back to the system the program has
crashed!!!!!!
10Exception Creation, Throwing, and Propagation
public class StarFirstName String stars
"Alan Ladd", "Frank Sinatra", "Madonna", "Brad
Pitt", "Mario Lanza", "John
Wayne", "Roy and Dale", "Sharon Stone", "Bert
Parks" public static void main(String
args) if( args.length 0 )
System.exit(0) String starfirstname
args0 StarFirstName me new
StarFirstName() try
me.middleman(starfirstname) catch(
Exception e) System.out.println("Got
Exception") e.printStackTrace()
finally System.out.println("I
hope you didn't put in a bad first
name!!!") public void middleman(String
firstname)throws BadStarException System.out.
println("Entered middleman") troublespot(firstn
ame) System.out.println("Leaving
middleman") public void troublespot(String
firstname) throws BadStarException int I
System.out.println("Entered troublespot") for(
I0 I starsI.startsWith(firstname)) break if(
I stars.length ) throw new BadStarException()
else System.out.println("Star Full Name "
starsI) System.out.println("Leaving
troublespot") class BadStarException
extends Exception public BadStarException()
super("Bad Movie Star First Name")
11Output of Star First Name Program
OUTPUT ON TWO RUNS, ONE GOOD, ONE
BAD!! java StarFirstName John Entered
middleman Entered troublespot Star Full Name
John Wayne Leaving troublespot Leaving
middleman I hope you didn't put in a bad first
name!!! java StarFirstName Duke Entered
middleman Entered troublespot Got
Exception BadStarException Bad Movie Star First
Name at StarFirstName.troublespot(StarFirs
tName.java34) at StarFirstName.middleman(
StarFirstName.java25) at
StarFirstName.main(StarFirstName.java11) I hope
you didn't put in a bad first name!!! C\users\el
yit\JavaClass\Exceptions
12Another Example Selecting Your Favorite Stars
By Index
public class SelectaStar String stars
"Alan Ladd", "Frank Sinatra", "Madonna", "Brad
Pitt", "Mario Lanza", "John Wayne", "Roy and
Dale", "Sharon Stone", "Bert Parks"
public static void main(String
args) throws ArrayIndexOutOfBoundsException i
f( args.length 0 ) System.exit(0) int
starIndex Integer.parseInt(args0) SelectaSt
ar me new SelectaStar() try me.middlem
an(starIndex) catch( Exception e)
System.out.println("Got Exception")
e.printStackTrace() finally Syste
m.out.println("I hope you didn't put in a bad
index!!!") public void middleman(int
x) System.out.println("Entered
middleman") troublespot(x) System.out.printl
n("Leaving middleman") public void
troublespot(int x) System.out.println("Ente
red troublespot") System.out.println("The Star
you chose was " starsx) System.out.println
("Leaving troublespot")
13Exception Propagation Selecting Your Favorite
Stars - Output
OUTPUT ON TWO RUNS, ONE GOOD, ONE BAD!! java
SelectaStar 5 Entered middleman Entered
troublespot The Star you chose was John
Wayne Leaving troublespot Leaving middleman I
hope you didn't put in a bad index!!! java
SelectaStar 55 Entered middleman Entered
troublespot Got Exception java.lang.ArrayIndexOutO
fBoundsException at SelectaStar.troublespo
t(SelectaStar.java32) at
SelectaStar.middleman(SelectaStar.java25)
at SelectaStar.main(SelectaStar.java11) I hope
you didn't put in a bad index!!!