Title: Exception Handling
1Exception Handling
syllabus
- Run-time errors
- The exception concept
- Throwing exceptions
- Handling exceptions
- Declaring exceptions
basic programming concepts
object oriented programming in Java
topics in computer science
2Run-time errors
- Sometimes when the computer tries to execute a
statement something goes wrong - reading a file that does not exist or is
inaccessible - dividing a number by zero
- calling a method with improper arguments
- In these cases we say that a run-time error has
occurred - In Java, run-time errors are indicated by
exceptions
3Exceptions
- If a method wants to signal that something went
wrong during its execution, it throws an
exception exceptions may be caught and handled
by another part of the program - Throwing an exception involves
- creating an exception object that encloses
information about the problem that occurred - use of the statement throw to notify about the
exception - A program can therefore be separated into a
normal execution flow and an exception execution
flow
4Example throwing an exception
- // Sets the time of the clock
- // _at_param hour, minute, second - Tthe new time
- public void setTime(int hour, int minute, int
second) - if (hourlt0 hourgt59 minutelt0
minutegt59 - secondlt0 secondgt59)
- throw new IllegalArgumentException(
- Invalid time)
-
- this.hour hour
- this.minute minute
- this.second second
5The exception object
- The information about the problem that occurred
is enclosed in an exception object, including - The type of the problem
- The place in the code where the exception
occurred - The state of the run-time stack
- ... other information
- An exception object comes with service methods
such as getMessage or printStackTrace - The code that invoked the illegal operation will
receive the exception object
6The type of the exception
- The most important information is the type of the
exception, indicated by the class of the
exception object - The Java API defines classes for many types of
exceptions (and you can define more of your own) - java.lang.ArithmeticException - thrown when an
exceptional arithmetic condition occurs, e.g.,
division by zero - java.io.FileNotFoundException - signals that a
file we tried to access could not be found - java.net.UnknownHostException - signals that a
computer we tried to communicate with cannot be
located - NullPointerException - trying to refer to an
object through a reference variable whose value
is null
7Example
- The setTime() method used the exception
java.lang.IllegalArgumentException to signal that
the values of the arguments were not valid - A method throws this type of exception if it
wants to signal that an argument it got is not
legal
8Occurrence of an exception
- When a program performs an illegal operation the
following happens - An exception object is created and thrown
- The regular flow of the program stops
- The program may try to handle the exceptional
situation - If the program ignores the exception, execution
stops we sometimes say that the program crashed
9Occurrence of an exception
- // ...
- class BucketsProblem
- public static void main(String args)
- // ...
- int targetCapacity 2x-y
- Bucket a new Bucket(x)
- Bucket b new Bucket(x)
- Bucket c new Bucket(y)
- Bucket target new Bucket(targetCapacity)
- // ...
-
-
- What happens if xlt0 or ylt0 or 2x-ylt0 ?
10The root of the exception
- in class Bucket (Bucket.java)
- // Constructs a new Bucket.
- // _at_param capacity the capacity of the
bucket - // _at_exception IllegalArgumentException if the
- // given capacity is negative
- public Bucket(int capacity)
- if (capacitylt0)
- throw new IllegalArgumentException(
- Capacity must be positive!)
-
- this.capacity capacity
-
11Occurrence of an exception
- public static void main(String args)
- // ...
- int z 2x-y // capacity of target
bucket - Bucket a new Bucket(x)
- Bucket b new Bucket(x)
- Bucket c new Bucket(y)
- Bucket target new Bucket(z)
- // ... the solution of the problem
-
-
x -3
A bucket must have a positive capacity
Hey, no one cares to listen!
Ill crash the method!
12Occurrence of an exception
A bucket must have a positive capacity. No one
cares, ... Ill crash the method
- public static void main(String args)
- // ...
- int z 2x-y // capacity of target
bucket - Bucket a new Bucket(x)
- Bucket b new Bucket(x)
- Bucket c new Bucket(y)
- Bucket target new Bucket(z)
- // ... the solution of the problem
-
-
x -3
capacity -3
public Bucket(int capacity) if (capacitylt0)
throw new IllegalArgumentException(
Capacity must be positive!)
this.capacity capacity
13Exceptions happen
- Sometimes we cannot avoid an exceptional state
for example when reading from a diskette we
cannot tell if the diskette is readable or not
without trying to read from it - Sometimes we want to handle the exceptional case
outside the main block, so as not to complicate
the readability of the code - If we ignore the exception, the program crashes
14Exception Handling
- A program can deal with an exception in one of
three ways - ignore it (the program will crash)
- handle it where it occurs
- handle it an another place in the program
15Handling Exceptions
- To process an exception when it occurs, the line
that throws the exception is executed within a
try block - A try block is followed by one or more catch
clauses, which contain code to process an
exception - Each catch clause has an associated exception
type - When an exception occurs, processing continues at
the first catch clause that matches the exception
type
16Handling exceptions
- public static void main(String args)
- // ...
- try
- int z 2x-y // capacity of target
bucket - Bucket a new Bucket(x)
- Bucket b new Bucket(x)
- Bucket c new Bucket(y)
- Bucket target new Bucket(z)
- // ... the solution of the problem
- catch (IllegalArgumentException ia)
- output.println(Illegal input!)
-
-
-
A bucket must have a positive capacity
17Handling exceptions
- public static void main(String args)
- // ...
- try
- int z 2x-y // capacity of target
bucket - Bucket a new Bucket(x)
- Bucket b new Bucket(x)
- Bucket c new Bucket(y)
- Bucket target new Bucket(z)
- // ... the solution of the problem
- catch (ArithmeticException ae)
- // ...
- catch (IllegalArgumentException ia)
- output.println(Illegal input!)
-
-
A bucket must have a positive capacity
18The finally Clause
- A try statement can have an optional clause
designated by the reserved word finally - If no exception is generated, the statements in
the finally clause are executed after the
statements in the try block finish their
execution - In addition, if an exception is generated, the
statements in the finally clause are executed
after the statements in the appropriate catch
clause complete execution
19Exception Propagation
- If it is not appropriate to handle the exception
where it occurs, it can be handled at a higher
level - Exceptions propagate up through the method
calling hierarchy until they are caught and
handled or until they reach the outermost level - Any try block along the way, that contains a call
to a method in which an exception is thrown, can
be used to catch that exception
20The throw Statement
- A programmer can define an exception by extending
the appropriate class - Exceptions are thrown using the throw statement
- Usually a throw statement is nested inside an if
statement that evaluates the condition to see if
the exception should be thrown
21Generating Exception Objects
- All the classes for indicating run-time errors
are derived from the class java.lang.Throwable - The object you deliver to the throw statement
must be an instance of class Throwable - The constructor of class Throwable initializes
all the information about the location where the
exception occurred, the state of the run-time
stack etc (thus this information is set for every
exception object)
22Exceptions class hierarchy
Throwable
Error
Exception
RuntimeException
23Exception Error distinction
- java.lang.Throwable has two direct subclasses
java.lang.Error and java.lang.Exception - Every run-time error is identified by a class
that is either a subclass of Error or of
Exception - The distinction is not very strict
- Error refers to run-time errors that are rooted
in the execution environment and are not in the
hands of the application programmer - Exception refers to all other run-time errors
the application programmer is responsible to see
that all exceptions are handled
24Errors examples
- java.lang.InternalError - signals an error caused
by an implementation bug in the JVM in which the
application is running the developer is not
responsible for this error and should not try to
handle it - java.lang.NoSuchMethodError - signals that a
method that the application is trying to use does
not exist this may happen if the application is
not installed correctly - java.lang.OutOfMemory - signals that the
application ran out of memory
25Exception examples
- java.lang.ArithmeticException - occurs when you
divide an integer by 0 the exception is rooted
in the logic of the application, hence it is the
programmer responsibility to handle it - java.io.FileNotFoundException - occurs when the
application tries to access a file which does not
exist again, the programmer should treat this
case - ...
26Errors and Exceptions
- The application you write must handle all
Exceptions but ignore Errors - If an Error occurs you should let it crash the
application the user will be notified for the
error and act accordingly (buy more memory,
reinstall the application, call tech support ...) - On the other hand, its very uncool to let the
application crash because you didnt catch an
exception
27Exceptions class hierarchy
Throwable
Error
Exception
RuntimeException
28Exceptions vs. RuntimeExcepiton
- Class Exception has a special subclass named
RuntimeException, which makes another
classification of exceptions runtime-exceptions
vs. regular exceptions - RuntimeException is characterized by
- The programmer could avoid the occurrence of the
exception - The exception can be thrown by common
statements/methods - The name RuntimeException is confusing every
exception and Error occurs during the run-time of
the application
29RuntimeException examples
- java.lang.ArithmeticException
- java.lang.NullPointerException
- java.lang.IllegalArgumentException
- java.lang.NegativeArraySizeException
- java.lang.ArrayIndexOutOfBoundsException
30Declaring for exceptions
- A method must declare all the non run-time
exceptions it may throw - The declaration for exceptions a method can throw
is done using the throws keyword - The user of the method is warned against possible
exceptions this method can throw - The exceptions that might be thrown by a method
should also be documented with the _at_exception tag
31Example (using throws)
- // Creates an ElectronicGate of a given type
- public ElectronicGate createGate(String type)
- throws UnkownGateException
- type type.toUpperCase()
- if (type.equals(OR))
- return new OrGate()
-
- if (type.equals(AND))
- return new AndGate()
-
- if (type.equals(NOT))
- return new NotGate()
-
- throw new UnknownGateException()
-
32Declaring for exceptions
- Because there is a possibility that an execution
of createGate() will throw an UnknownGateException
which is not a RuntimeException, createGate()
must declare this exception - If you try to call the createGate() method from
another method, the compiler will know that there
is a possibility that this method will throw an
UnknownGateException it will then force you to - try to catch this exception
- or
- declare that the calling method also throws this
type of exception
33Example either catch ...
- // Called when the user chooses to add a gate
- private void userAddsGate()
- String type ... look up the selected gate
type - try
- Gate gate createGate(type)
- GateFigure figure createGateFigure(type)
- ... adds the gate to the model
- ... add the figure to the display
- ...
- catch (UnknownGateException uge)
- // ignore this, dont add the gate
-
-
-
34... or declare
- // Called when the user chooses to add a gate
- private void userAddsGate()
- throws UnknownGateException
- String type ... look up the selected gate
type - Gate gate createGate(type)
- GateFigure figure createGateFigure(type)
- ... adds the gate to the model
- ... add the figure to the display
- ...
-
-
35Defining new exception type
- // An exception thrown to indicate that a
requested - // type of electronic gate does not exist
- public class UnknownGateException extends
Exception -
- // Creates a new UnknownGateException
- public UnknownGateException()
- super(This is an illegal gate type!)
-
- // Creates a new UnknownGateException
- public UnknownGateException(String cause)
- super(cause)
-
36Several notes
- The throws statement doesnt affect the way the
exception will be treated in run-time - You can also declare for RuntimeExceptions, but
it is not necessary - When to declare and when to catch the exception
within the method is a design decision
37Exaple class MyDate
- public class MyDate
- public static final int JANUARY 1
- public static final int FEBRUARY 2
- //data members
- public int day
- private int month
- private int year
- //default constructor - recieves no
paramaters - public MyDate()
- day 1
- month 1
- year 2000
-
38Exaple class MyDate
- //insertion constructor
- public MyDate(int day,int month,int year)
throws IllegalMyDateException - if (!legalDate(day,month,year))
- throw new IllegalMyDateException()
- this.day day
- this.month month
- this.year year
-
- private boolean legalDate(int day,int month,int
year) - if ( (day lt1) (day gt 31) (monthlt1)
(monthgt12) ) - return(false)
- return(true)
-
39Exception class definition
- public class IllegalMyDateException extends
Exception -
- public IllegalMyDateException(String message)
- super(message)
-
-
- public IllegalMyDateException()
- super("this is not a legal date!")
-