1 exception handling starring: arrayindexoutofbounds co-starring: ariane rocket ioexception...

61
1 Exception Handling Starring: ArrayIndexOutOfBOunds Co-Starring: Ariane Rocket IOException RunTImeException

Upload: russell-mcdaniel

Post on 04-Jan-2016

217 views

Category:

Documents


1 download

TRANSCRIPT

Page 1: 1 Exception Handling Starring: ArrayIndexOutOfBOunds Co-Starring: Ariane Rocket IOException RunTImeException

1

Exception Handling

Starring: ArrayIndexOutOfBOunds

Co-Starring: Ariane Rocket

IOException

RunTImeException

Page 2: 1 Exception Handling Starring: ArrayIndexOutOfBOunds Co-Starring: Ariane Rocket IOException RunTImeException

2

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.

Page 3: 1 Exception Handling Starring: ArrayIndexOutOfBOunds Co-Starring: Ariane Rocket IOException RunTImeException

3

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

Page 4: 1 Exception Handling Starring: ArrayIndexOutOfBOunds Co-Starring: Ariane Rocket IOException RunTImeException

4

Resources:

Barrons:

Page 15-16Pages 41, 79, 170, 180, 250, 252, 255,

375

Page 5: 1 Exception Handling Starring: ArrayIndexOutOfBOunds Co-Starring: Ariane Rocket IOException RunTImeException

5

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

Page 6: 1 Exception Handling Starring: ArrayIndexOutOfBOunds Co-Starring: Ariane Rocket IOException RunTImeException

6

AP AB Subset Requirements:

Students are expected to understand the exceptions that occur when their programs contain errors , in particular:

NullPointerException ArrayIndexOutOfBoundsException

ArithmeticException ClassCastException

Page 7: 1 Exception Handling Starring: ArrayIndexOutOfBOunds Co-Starring: Ariane Rocket IOException RunTImeException

7

Students are expected to be able to throw the unchecked IllegalStateException and NoSuchElementException in their own methods (principally when implementing collection ADTs).

Page 8: 1 Exception Handling Starring: ArrayIndexOutOfBOunds Co-Starring: Ariane Rocket IOException RunTImeException

8

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

Page 9: 1 Exception Handling Starring: ArrayIndexOutOfBOunds Co-Starring: Ariane Rocket IOException RunTImeException

9

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

Page 10: 1 Exception Handling Starring: ArrayIndexOutOfBOunds Co-Starring: Ariane Rocket IOException RunTImeException

10

Exceptions are divided into two categories:

Exceptions that Java REQUIRES the programmer to handle

IOException is one that MUST be handled

Page 11: 1 Exception Handling Starring: ArrayIndexOutOfBOunds Co-Starring: Ariane Rocket IOException RunTImeException

11

Exceptions that the programmer has the option of handling

ArithmeticException

ArrayIndexOutOfBoundsException

Page 12: 1 Exception Handling Starring: ArrayIndexOutOfBOunds Co-Starring: Ariane Rocket IOException RunTImeException

12

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);

}

Page 13: 1 Exception Handling Starring: ArrayIndexOutOfBOunds Co-Starring: Ariane Rocket IOException RunTImeException

13

// 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);

}

Page 14: 1 Exception Handling Starring: ArrayIndexOutOfBOunds Co-Starring: Ariane Rocket IOException RunTImeException

14

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

Page 15: 1 Exception Handling Starring: ArrayIndexOutOfBOunds Co-Starring: Ariane Rocket IOException RunTImeException

15

You can have these combined:// catch division by zerotry{

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);}

Page 16: 1 Exception Handling Starring: ArrayIndexOutOfBOunds Co-Starring: Ariane Rocket IOException RunTImeException

16

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)

Page 17: 1 Exception Handling Starring: ArrayIndexOutOfBOunds Co-Starring: Ariane Rocket IOException RunTImeException

17

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

Page 18: 1 Exception Handling Starring: ArrayIndexOutOfBOunds Co-Starring: Ariane Rocket IOException RunTImeException

18

Look at our File I/O processing:

// instiantate a buffer to hold a chunk of the fileBufferedReader br = new BufferedReader(reader);

// read in 1 line of the file into the buffertry

{linein = br.readLine();

} catch (IOException e)

{linein = new String("-- An error has occurred

--");}

Page 19: 1 Exception Handling Starring: ArrayIndexOutOfBOunds Co-Starring: Ariane Rocket IOException RunTImeException

19

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

Page 20: 1 Exception Handling Starring: ArrayIndexOutOfBOunds Co-Starring: Ariane Rocket IOException RunTImeException

20

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

Page 21: 1 Exception Handling Starring: ArrayIndexOutOfBOunds Co-Starring: Ariane Rocket IOException RunTImeException

21

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

Page 22: 1 Exception Handling Starring: ArrayIndexOutOfBOunds Co-Starring: Ariane Rocket IOException RunTImeException

22

Unchecked Exceptions:

RunTime Exceptions can occur almost anywhere

These kind of errors are the programmers fault !!!

Unchecked exceptions halt the program

Page 23: 1 Exception Handling Starring: ArrayIndexOutOfBOunds Co-Starring: Ariane Rocket IOException RunTImeException

23

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

Page 24: 1 Exception Handling Starring: ArrayIndexOutOfBOunds Co-Starring: Ariane Rocket IOException RunTImeException

24

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:

Page 25: 1 Exception Handling Starring: ArrayIndexOutOfBOunds Co-Starring: Ariane Rocket IOException RunTImeException

25

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

Page 26: 1 Exception Handling Starring: ArrayIndexOutOfBOunds Co-Starring: Ariane Rocket IOException RunTImeException

26

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)

Page 27: 1 Exception Handling Starring: ArrayIndexOutOfBOunds Co-Starring: Ariane Rocket IOException RunTImeException

27

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)

Page 28: 1 Exception Handling Starring: ArrayIndexOutOfBOunds Co-Starring: Ariane Rocket IOException RunTImeException

28

Students need to be able to throw the Unchecked exceptions:

IllegalStateException --- Signals that a method has been invoked at an illegal or inappropriate time

Page 29: 1 Exception Handling Starring: ArrayIndexOutOfBOunds Co-Starring: Ariane Rocket IOException RunTImeException

29

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

Page 30: 1 Exception Handling Starring: ArrayIndexOutOfBOunds Co-Starring: Ariane Rocket IOException RunTImeException

30

In these Examples of Exceptions, what type of exception would occur ?

int num = 21;

int count = 0;

System.out.println(num / count);

Page 31: 1 Exception Handling Starring: ArrayIndexOutOfBOunds Co-Starring: Ariane Rocket IOException RunTImeException

31

In these Examples of Exceptions, what type of exception would occur ?

int num = 21;

int count = 0;

System.out.println(num / count);

ANS: ArithmeticException

Page 32: 1 Exception Handling Starring: ArrayIndexOutOfBOunds Co-Starring: Ariane Rocket IOException RunTImeException

32

(Manager is a subclass of an Employee class)

Employee worker1 = new Employee( );

System.out.println((Manager)worker1);

Page 33: 1 Exception Handling Starring: ArrayIndexOutOfBOunds Co-Starring: Ariane Rocket IOException RunTImeException

33

(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

Page 34: 1 Exception Handling Starring: ArrayIndexOutOfBOunds Co-Starring: Ariane Rocket IOException RunTImeException

34

int[ ] anArray = new int[10];

anArray[11] = o;

Page 35: 1 Exception Handling Starring: ArrayIndexOutOfBOunds Co-Starring: Ariane Rocket IOException RunTImeException

35

int[ ] anArray = new int[10];

anArray[11] = o;

ANS:ArrayIndexOutOfBoundsException

Page 36: 1 Exception Handling Starring: ArrayIndexOutOfBOunds Co-Starring: Ariane Rocket IOException RunTImeException

36

String s = “string”;

System.out.println(s.substring(0,8));

Page 37: 1 Exception Handling Starring: ArrayIndexOutOfBOunds Co-Starring: Ariane Rocket IOException RunTImeException

37

String s = “string”;

System.out.println(s.substring(0,8));

ANS:StringIndexOutOfBOundsException

Page 38: 1 Exception Handling Starring: ArrayIndexOutOfBOunds Co-Starring: Ariane Rocket IOException RunTImeException

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( ) );

Page 39: 1 Exception Handling Starring: ArrayIndexOutOfBOunds Co-Starring: Ariane Rocket IOException RunTImeException

39

(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

Page 40: 1 Exception Handling Starring: ArrayIndexOutOfBOunds Co-Starring: Ariane Rocket IOException RunTImeException

40

The for loop iterator traverses the entire array so the final output asks for the next element in the ArrayList that does not exist

Page 41: 1 Exception Handling Starring: ArrayIndexOutOfBOunds Co-Starring: Ariane Rocket IOException RunTImeException

41

Manager worker1 = null;

String temp = worker1.getName( );

Page 42: 1 Exception Handling Starring: ArrayIndexOutOfBOunds Co-Starring: Ariane Rocket IOException RunTImeException

42

Manager worler1 = null;

String temp = worker1.getName( );

ANS: NullPointerException;

Page 43: 1 Exception Handling Starring: ArrayIndexOutOfBOunds Co-Starring: Ariane Rocket IOException RunTImeException

43

int units = Integer.parseInt(“1234a”);

System.out.println(units + 1);

Page 44: 1 Exception Handling Starring: ArrayIndexOutOfBOunds Co-Starring: Ariane Rocket IOException RunTImeException

44

int units = Integer.parseInt(“1234a”);

System.out.println(units + 1);

ANS: NumberFormatException

as “1234a” is not a valid number

Page 45: 1 Exception Handling Starring: ArrayIndexOutOfBOunds Co-Starring: Ariane Rocket IOException RunTImeException

45

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

Page 46: 1 Exception Handling Starring: ArrayIndexOutOfBOunds Co-Starring: Ariane Rocket IOException RunTImeException

46

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

Page 47: 1 Exception Handling Starring: ArrayIndexOutOfBOunds Co-Starring: Ariane Rocket IOException RunTImeException

47

if (withDrawAmount > balance)

{

IllegalArgumentException exception = new

IllegalArgumentException(“Amount exceeds Balance”);

throw exception;

}

else

balance -= wothDrawAmount;

Page 48: 1 Exception Handling Starring: ArrayIndexOutOfBOunds Co-Starring: Ariane Rocket IOException RunTImeException

48

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

Page 49: 1 Exception Handling Starring: ArrayIndexOutOfBOunds Co-Starring: Ariane Rocket IOException RunTImeException

49

Students must be able to THROW exceptions:

if (radius < 0)

throw new IllegalArgumentException (“bad radius value”);

else

I = Math.Pi * r * r;

Page 50: 1 Exception Handling Starring: ArrayIndexOutOfBOunds Co-Starring: Ariane Rocket IOException RunTImeException

50

Unchecked errors do not require try / catch

The exceptions students will be required to throw are:

IllegalArgumentException IllegalStateException NoSuchElementException

Page 51: 1 Exception Handling Starring: ArrayIndexOutOfBOunds Co-Starring: Ariane Rocket IOException RunTImeException

51

Examples:public void race(double raceLength){

if (raceLength < = 0){ throw new IllegalArgumentException(“Race length must be greater than zero”);}numberOfRaces++;milesRaced += raceLength;

}

Page 52: 1 Exception Handling Starring: ArrayIndexOutOfBOunds Co-Starring: Ariane Rocket IOException RunTImeException

52

public BankAccount (double initialBalance)

{

if (initialBalance < 0)

{

throw new IllegalStateException(“Initial balance must be non-negative”);

}

balance = initialBalance;

}

Page 53: 1 Exception Handling Starring: ArrayIndexOutOfBOunds Co-Starring: Ariane Rocket IOException RunTImeException

53

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

Page 54: 1 Exception Handling Starring: ArrayIndexOutOfBOunds Co-Starring: Ariane Rocket IOException RunTImeException

54

LinkedList myLL = new LinkedList;

myLL.remove( );

will result in a

NoSuchElementException

Page 55: 1 Exception Handling Starring: ArrayIndexOutOfBOunds Co-Starring: Ariane Rocket IOException RunTImeException

55

What is critical for the AP Exam:

Know the Conditions under which the common (listed in the previous section) exceptions are thrown

Page 56: 1 Exception Handling Starring: ArrayIndexOutOfBOunds Co-Starring: Ariane Rocket IOException RunTImeException

56

What is critical for the AP Exam:

Be able to throw the IllegalStateException and the NoSuchElementException in your own projects

Page 57: 1 Exception Handling Starring: ArrayIndexOutOfBOunds Co-Starring: Ariane Rocket IOException RunTImeException

57

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

Page 58: 1 Exception Handling Starring: ArrayIndexOutOfBOunds Co-Starring: Ariane Rocket IOException RunTImeException

58

Java Docs:

Open up Java Docs and look at the exceptions the ArrayList, for example, throws

Page 59: 1 Exception Handling Starring: ArrayIndexOutOfBOunds Co-Starring: Ariane Rocket IOException RunTImeException

59

Ariane Rocket Incident:

Discuss this ESA Story from Java Essentials Chapter 14 pp.576-577

Page 60: 1 Exception Handling Starring: ArrayIndexOutOfBOunds Co-Starring: Ariane Rocket IOException RunTImeException

60

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

Page 61: 1 Exception Handling Starring: ArrayIndexOutOfBOunds Co-Starring: Ariane Rocket IOException RunTImeException

61

NO Specific Test for This Section !!!