Download unit 10

Survey
yes no Was this document useful for you?
   Thank you for your participation!

* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project

Document related concepts
no text concepts found
Transcript
Exception 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
1
unit 10
Run-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
2
unit 10
Exceptions

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
3
unit 10
Example: throwing an exception
// Sets the time of the clock
// @param hour, minute, second - Tthe new time
public void setTime(int hour, int minute, int second) {
if (hour<0 || hour>59 || minute<0 || minute>59 ||
second<0 || second>59) {
throw new IllegalArgumentException(
“Invalid time”);
}
this.hour = hour;
this.minute = minute;
this.second = second;
}
4
unit 10
The 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
5
unit 10
The 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
6
through a reference variable whose value is null
unit 10
Example


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
7
unit 10
Occurrence 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
8
unit 10
Occurrence of an exception
// ...
class BucketsProblem {
public static void main(String[] args) {
// ...
int targetCapacity = 2*x-y;
Bucket a = new Bucket(x);
Bucket b = new Bucket(x);
Bucket c = new Bucket(y);
Bucket target = new Bucket(targetCapacity);
// ...
}
}

What happens if x<0 or y<0 or 2x-y<0 ?
9
unit 10
The root of the exception
in class Bucket (Bucket.java):
//
//
//
//
Constructs a new Bucket.
@param capacity: the capacity of the bucket
@exception: IllegalArgumentException if the
given capacity is negative
public Bucket(int capacity) {
if (capacity<0) {
throw new IllegalArgumentException(
“Capacity must be positive!”);
}
this.capacity = capacity;
}
10
unit 10
Occurrence of an exception
public static void main(String[] args) {
// ...
x = -3
int z = 2*x-y; // capacity of target bucket
Bucket a = new Bucket(x);
Bucket b = new Bucket(x);
Bucket c = new Bucket(y);
A bucket must
have a positive
Bucket target = new Bucket(z);
capacity
// ... the solution of the problem
}
Hey, no one
cares to
listen!
I’ll crash the
method!
11
unit 10
Occurrence of an exception
A bucket must
have a positive
capacity.
No one cares, ...
I’ll crash the method
public static void main(String[] args) {
x = -3
// ...
int z = 2*x-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
}
capacity = -3
public Bucket(int capacity) {
if (capacity<0) {
throw new IllegalArgumentException(
“Capacity must be positive!”);
}
this.capacity = capacity;
}
12
}
unit 10
Exceptions 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
13
unit 10
Exception 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
14
unit 10
Handling 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
15
unit 10
Handling exceptions
public static void main(String[] args) {
// ...
try {
int z = 2*x-y; // capacity of target bucket
Bucket a = new Bucket(x);
Bucket b = new Bucket(x);
A bucket must
Bucket c = new Bucket(y);
have a positive
Bucket target = new Bucket(z);
capacity
// ... the solution of the problem
} catch (IllegalArgumentException ia) {
output.println(“Illegal input!”);
}
}
16
unit 10
Handling exceptions
public static void main(String[] args) {
// ...
try {
int z = 2*x-y; // capacity of target bucket
Bucket a = new Bucket(x);
Bucket b = new Bucket(x);
A bucket must
Bucket c = new Bucket(y);
have a positive
Bucket target = new Bucket(z);
capacity
// ... the solution of the problem
} catch (ArithmeticException ae) {
// ...
} catch (IllegalArgumentException ia) {
output.println(“Illegal input!”);
}
}
17
unit 10
The 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
18
unit 10
Exception 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
19
unit 10
The 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
20
unit 10
Generating 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)
21
unit 10
Exceptions class hierarchy
Throwable
Error
Exception
RuntimeException
22
unit 10
Exception & 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
23
unit 10
Errors 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
24
unit 10
Exception 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

...
25
unit 10
Errors 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, it’s very uncool to let the
application crash because you didn’t catch an
exception
26
unit 10
Exceptions class hierarchy
Throwable
Error
Exception
RuntimeException
27
unit 10
Exceptions 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
28
unit 10
RuntimeException examples

java.lang.ArithmeticException

java.lang.NullPointerException

java.lang.IllegalArgumentException

java.lang.NegativeArraySizeException

java.lang.ArrayIndexOutOfBoundsException
29
unit 10
Declaring 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 @exception
tag
30
unit 10
Example (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();
}
31
unit 10
Declaring 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
32
unit 10
Example: 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, don’t add the gate
}
}
33
unit 10
... 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
...
}
34
unit 10
Defining 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);
}
}
35
unit 10
Several notes

The throws statement doesn’t 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
36
unit 10
Exaple: 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;
}
37
unit 10
Exaple: 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 <1) || (day > 31) || (month<1) || (month>12) )
return(false);
return(true);
}
}
38
unit 10
Exception class definition
public class IllegalMyDateException extends Exception {
public IllegalMyDateException(String message){
super(message);
}
public IllegalMyDateException(){
super("this is not a legal date!");
}
}
39
unit 10