Exceptions and exception handling in computerized information
Unit 10 1 Exception Handling H Run-time errors H The exception concept H Throwing exceptions H...
-
date post
19-Dec-2015 -
Category
Documents
-
view
252 -
download
2
Transcript of Unit 10 1 Exception Handling H Run-time errors H The exception concept H Throwing exceptions H...
1unit 10
Exception HandlingException Handling
Run-time errors The exception concept Throwing exceptions Handling exceptions Declaring exceptions
basic programming
concepts
object oriented programming
in Java
topics in computer science
syllabus
2unit 10
Run-time errorsRun-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
3unit 10
ExceptionsExceptions
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
4unit 10
Example: throwing an exceptionExample: 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;
}
5unit 10
The exception objectThe 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
6unit 10
The type of the exceptionThe 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
7unit 10
ExampleExample
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
8unit 10
Occurrence of an exceptionOccurrence 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
9unit 10
Occurrence of an exceptionOccurrence 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 ?
10unit 10
The root of the exceptionThe 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; }
11unit 10
Occurrence of an exceptionOccurrence of an exception
public static void main(String[] args) {
// ...
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
}
A bucket must
have a positive
capacity
Hey, no one
cares to
listen!
I’ll crash the
method!
x = -3
12unit 10
Occurrence of an exceptionOccurrence of an exception
public static void main(String[] args) { // ... 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 }
A bucket must
have a positive
capacity.
No one cares, ...
I’ll crash the methodx = -3
public Bucket(int capacity) { if (capacity<0) { throw new IllegalArgumentException( “Capacity must be positive!”); } this.capacity = capacity; }}
capacity = -3
13unit 10
Exceptions happenExceptions 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
14unit 10
Exception HandlingException 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
15unit 10
Handling ExceptionsHandling 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
16unit 10
Handling exceptionsHandling 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); 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
17unit 10
Handling exceptionsHandling 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); 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
18unit 10
The The finallyfinally Clause 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
19unit 10
Exception PropagationException 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
20unit 10
The The throwthrow Statement 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
21unit 10
Generating Exception ObjectsGenerating 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)
22unit 10
Exceptions class hierarchyExceptions class hierarchy
Throwable
ExceptionError
RuntimeException
23unit 10
Exception & Error distinctionException & 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
24unit 10
Errors examplesErrors 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
25unit 10
Exception examplesException 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
...
26unit 10
Errors and ExceptionsErrors 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
27unit 10
Exceptions class hierarchyExceptions class hierarchy
Throwable
ExceptionError
RuntimeException
28unit 10
Exceptions vs. RuntimeExcepitonExceptions 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
29unit 10
RuntimeException examplesRuntimeException examples
java.lang.ArithmeticException
java.lang.NullPointerException
java.lang.IllegalArgumentException
java.lang.NegativeArraySizeException
java.lang.ArrayIndexOutOfBoundsException
30unit 10
Declaring for exceptionsDeclaring 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
31unit 10
Example (using throws)Example (using throws)
// Creates an ElectronicGate of a given typepublic 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();}
32unit 10
Declaring for exceptionsDeclaring 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 exceptionor• declare that the calling method also throws this type
of exception
33unit 10
Example: either catch ...Example: either catch ...
// Called when the user chooses to add a gateprivate 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 }}
34unit 10
... or declare... 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
...
}
35unit 10
Defining new exception typeDefining new exception type
// An exception thrown to indicate that a requested// type of electronic gate does not existpublic 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); }}
36unit 10
Several notesSeveral 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
37unit 10
Exaple: class MyDateExaple: class MyDate
public class MyDate { public static final int JANUARY= 1; public static final int FEBRUARY= 2;
//data memberspublic int day;private int month;private int year;
//default constructor - recieves no paramaterspublic MyDate() {day= 1;month= 1;year= 2000;}
38unit 10
Exaple: class MyDateExaple: 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);
}}