Exception Handling

Download Report

Transcript Exception Handling

Exception Handling
Starring: ArrayIndexOutOfBOunds
Co-Starring: Ariane Rocket
IOException
RunTImeException
1
Purpose:
In this lecture series we will learn about
Exception Handling.
Our programs need to be able to handle
run time problems that may arise due
to logic or other flaws in our programs.
We need to be able to recognize the
common exception errors as well as
throw our own exceptions to be able to
handle unexpected run time problems.
2
 Resources:
Java Essentials Chapter 14 p.557
Java Essentials Study Guide Chapter
12 p.195
Lambert Comprehensive Appendix F
Big Java Chapter 14 p. 557
Deitel & Deitel “Java How to Program”
Chapter 14 p.698
3
 Resources:
Barrons:
Page 15-16
Pages 41, 79, 170, 180, 250, 252, 255,
375
4
Intro:
Exception handling is necessary as
many Java methods require you to deal
with the possibility that the method will
not work as specified.

We will discuss:
The AP AB Requirements
Errors vs Exceptions
Checked Exceptions
UnChecked Exceptions
Throwing our own Exceptions
5
AP AB Subset Requirements:
Students are expected to understand
the exceptions that occur when their
programs contain errors , in particular:
NullPointerException
ArrayIndexOutOfBoundsException
ArithmeticException
ClassCastException
6
Students are expected to be able to
throw the unchecked
IllegalStateException and
NoSuchElementException in their own
methods (principally when
implementing collection ADTs).
7
Checked exceptions are not in the
subset. In particular, the
try/catch/finally statements is not in the
subset.
NOTE: Checked Exceptions &
Try/Catch/Finally are NOT IN THE AP
Subset
8
Errors vs Exceptions
Errors are serious Run Time problems
that usually are NOT practical to handle
in a program
For example, an infinite loop results in
Java throwing a StackOverflowError
Java defines a separate class for each
kind of error in java.lang.Error
9
Exceptions are divided into two
categories:
Exceptions that Java REQUIRES the
programmer to handle
IOException is one that MUST be handled
10
Exceptions that the programmer has
the option of handling
ArithmeticException
ArrayIndexOutOfBoundsException
11
 Examples of handling exceptions:
// catch division by zero
try
{
quotient = dividend / divisor;
System.out.println(“Successful division”);
}
catch (ArithmeticException e)
{
System.out.println(“ErrorA: “ + e.toString);
}
12
// catch to catch an index out of range
try
{
a[x] = 0;;
System.out.println(“Successful
Supscripting”);
}
catch (ArrayIndexOutOfBoundsException e)
{
System.out.println(“ErrorB: “ + e.toString);
}
13
When Java detects and throws an
exception, control is immediately
transferred from the problem
instruction in the try block to the catch
statement.
Therefore, if no exception occurs then
the remaining code in the try executes
completely and the catch code never
executes
14
 You can have these combined:
// catch division by zero
try
{
quotient = dividend / divisor;
System.out.println(“Successful division”);
a[x] = 0;;
System.out.println(“Successful Supscripting”);
}
catch (ArithmeticException e)
{
System.out.println(“ErrorA: “ + e.toString);
}
catch (ArrayIndexOutOfBoundsException e)
{
System.out.println(“ErrorB: “ + e.toString);
}
15
Checked Exceptions:
These are due to external
circumstances that the programmer
can not prevent
Therefore the compiler will make sure
your program handles these exceptions
(compiler forced)
16
When you call a method that throws a
checked exception, you MUST tell the
system what to do if the exception is
thrown
All children of IOException are checked
exceptions and these are the most
common types of Checked exceptions
17
 Look at our File I/O processing:
// instiantate a buffer to hold a chunk of the file
BufferedReader br = new BufferedReader(reader);
// read in 1 line of the file into the buffer
try
{
linein = br.readLine();
}
catch (IOException e)
{
linein = new String("-- An error has occurred --");
}
18
We were forced to handle possible IO
exceptions when we read from the
buffered reader
This is an example of a checked
exception
These exceptions describe a problem
that is likely to occur at times
regardless of how careful you are
19
 Checked errors ---- you must handle in your
code methods that throw exception errors
TRY CATCH
try
{
// IO stuff
} catch (IOException e)
{
// do some S.O.P error msg
// (use e)
}
 A Checked exception will occur only in the
context of a specific activity
20
Students do not need to write their own
checked exceptions but they need to be
able to read and understand them when
they occur in existing programs
21
Unchecked Exceptions:
RunTime Exceptions can occur almost
anywhere
These kind of errors are the
programmers fault !!!
Unchecked exceptions halt the
program
22
While a file I/O error can occur for
reasons out of your control, you are
responsible for a NullPointerException
because your code was badly designed
in trying to access a NULL reference
Java’s compiler does not force you to
handle these unchecked exceptions
23
NullPointerException and
IllegalArgumentException are examples
of unchecked exceptions
All exceptions that extend the class
java.lang.RuntimeException class are
Unchecked exceptions
Here is the list of unchecked
exceptions you are responsible for:
24
NullPointerException --- attempt to
access a Null Object
IllegalArgumentException --- An
argument supplied is not legal for that
method
ArrayIndexOutOfBoundsException --Attempt to access an index element
that is not in the Array’s range
25
ClassCastException --- Occurs when
an attempt is made to cast a variable to
a class that it does not match
ArithmeticException --- division by
ZERO for integers
IndexOutOfBoundsException --- thrown
when an index is out of range (parent of
ArrayIndex and StringIndex)
26
StringIndexOutOfBoundsException --Thrown when an index is out of the
range of the String’s size
NumberFormatException --- Thrown
when an attempt to convert a String to
one of the numeric types is made when
the String does not have the
appropriate format (child of
IllegalArgument)
27
Students need to be able to throw the
Unchecked exceptions:
IllegalStateException --- Signals that a
method has been invoked at an illegal
or inappropriate time
28
NoSuchElementException --- Thrown
when an attempt to access a
nonexistent element is made. Thrown
by the nextElement method of an
Enumeration to indicate that there are
no more elements in the enumeration
29
In these Examples of Exceptions, what
type of exception would occur ?
int num = 21;
int count = 0;
System.out.println(num / count);
30
In these Examples of Exceptions, what
type of exception would occur ?
int num = 21;
int count = 0;
System.out.println(num / count);
ANS:
ArithmeticException
31
(Manager is a subclass of an Employee
class)
Employee worker1 = new Employee( );
System.out.println((Manager)worker1);
32
(Manager is a subclass of an Employee
class)
Employee worker1 = new Employee( );
System.out.println((Manager)worker1);
ANS: ClassCastException as worker1
is an Employee NOT a Manager
33
int[ ] anArray = new int[10];
anArray[11] = o;
34
int[ ] anArray = new int[10];
anArray[11] = o;
ANS:
ArrayIndexOutOfBoundsException
35
String s = “string”;
System.out.println(s.substring(0,8));
36
String s = “string”;
System.out.println(s.substring(0,8));
ANS:
StringIndexOutOfBOundsException
37
(I know we have not discussed Iterator
yet, but try and reason this one out)
ArrayList friends = new ArrayList( );
Iterator it2;
for (it2 = friends.iterator( ); it2.hasNext( ) ;
)
{
String temp2 = (String)it2.next( );
System.out.println(temp2);
}
System.out.println(it2.next( ) );
38
(I know we have not discussed Iterator yet, but
try and reason this one out)
ArrayList friends = new ArrayList( );
Iterator it2;
for (it2 = friends.iterator( ); it2.hasNext( ) ; )
{
String temp2 = (String)it2.next( );
System.out.println(temp2);
}
System.out.println(it2.next( ) );
 ANS:
NoSuchElementException on the
last output
39
The for loop iterator traverses the
entire array so the final output asks for
the next element in the ArrayList that
does not exist
40
Manager worker1 = null;
String temp = worker1.getName( );
41
Manager worler1 = null;
String temp = worker1.getName( );
ANS:
NullPointerException;
42
int units = Integer.parseInt(“1234a”);
System.out.println(units + 1);
43
int units = Integer.parseInt(“1234a”);
System.out.println(units + 1);
ANS: NumberFormatException
as “1234a” is not a valid number
44
Throwing Exceptions:
Throwing exceptions can ensure that
certain conditions exist when your
programs are executed
Frequently, especially in the AP exam,
PRECONDITIONS are set for any caller
of a method to meet
45
However, we can ensure proper data by
checking ourselves
When you detect an error, you may
throw an appropriate exception
The throw statement is used to invoke
the exception handling mechanism
To throw an exception, you need to
create an instance of an Exception
Object with the new operator and then
throw it
46
if (withDrawAmount > balance)
{
IllegalArgumentException exception
= new
IllegalArgumentException(“Amount
exceeds Balance”);
throw exception;
}
else
balance -= wothDrawAmount;
47
You can simplify the exception
creation:
throw new
IllegalArgumentException(“Amount
exceeds Balance”);
At that point the current flow of your
code is interrupted and control passes
to the exception handler
48
Students must be able to THROW
exceptions:
if (radius < 0)
throw new
IllegalArgumentException (“bad
radius value”);
else
I = Math.Pi * r * r;
49
Unchecked errors do not require try /
catch
The exceptions students will be
required to throw are:



IllegalArgumentException
IllegalStateException
NoSuchElementException
50
Examples:
public void race(double raceLength)
{
if (raceLength < = 0)
{
throw new
IllegalArgumentException(“Race length
must be greater than zero”);
}
numberOfRaces++;
milesRaced += raceLength;
}
51
public BankAccount (double
initialBalance)
{
if (initialBalance < 0)
{
throw new
IllegalStateException(“Initial balance
must be non-negative”);
}
balance = initialBalance;
}
52
The NoSuchElementException will be
discussed when we learn about Linked
Lists
However, this error will result when a
Linked List attempts to remove the first
element from an empty List
Lets look at the Java Doc for
java.util.LinkedList and examine the
removeFirst method
53
LinkedList myLL = new LinkedList;
myLL.remove( );
will result in a
NoSuchElementException
54
What is critical for the AP Exam:
Know the Conditions under which the
common (listed in the previous section)
exceptions are thrown
55
What is critical for the AP Exam:
Be able to throw the
IllegalStateException and the
NoSuchElementException in your own
projects
56
What is critical for the AP Exam:
Students should understand these
unchecked exceptions:

NullPointerException
 ArrayIndexOutOfBOundsException

ArithmeticException (divide by zero)

ClassCastException
 IllegalArgumentException
IOException is also helpful to know
57
Java Docs:
Open up Java Docs and look at the
exceptions the ArrayList, for example,
throws
58
Ariane Rocket Incident:
Discuss this ESA Story from Java
Essentials Chapter 14 pp.576-577
59
Projects:
Various Multiple Choice and Free
Response Questions
All Barrons M/C and Free Response
Questions on Exception Handling
From this point forward, all potential
unchecked exceptions MUST be
handled
60
NO Specific Test for
This Section !!!
61