610 likes | 690 Views
Exception Handling. Starring: ArrayIndexOutOfBOunds Co-Starring: Ariane Rocket IOException RunTImeException. Purpose: In this lecture series we will learn about Exception Handling.
E N D
Exception Handling Starring: ArrayIndexOutOfBOunds Co-Starring: Ariane Rocket IOException RunTImeException
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.
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
Resources: • Barrons: • Page 15-16 • Pages 41, 79, 170, 180, 250, 252, 255, 375
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
AP AB Subset Requirements: • Students are expected to understand the exceptions that occur when their programs contain errors , in particular: NullPointerException ArrayIndexOutOfBoundsException ArithmeticException ClassCastException
Students are expected to be able to throw the unchecked IllegalStateException and NoSuchElementException in their own methods (principally when implementing collection ADTs).
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
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
Exceptions are divided into two categories: • Exceptions that Java REQUIRES the programmer to handle IOException is one that MUST be handled
Exceptions that the programmer has the option of handling ArithmeticException ArrayIndexOutOfBoundsException
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); }
// 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); }
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
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); }
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)
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
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 --"); }
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
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
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
Unchecked Exceptions: • RunTime Exceptions can occur almost anywhere • These kind of errors are the programmers fault !!! • Unchecked exceptions halt the program
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
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:
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
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)
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)
Students need to be able to throw the Unchecked exceptions: • IllegalStateException --- Signals that a method has been invoked at an illegal or inappropriate time
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
In these Examples of Exceptions, what type of exception would occur ? int num = 21; int count = 0; System.out.println(num / count);
In these Examples of Exceptions, what type of exception would occur ? int num = 21; int count = 0; System.out.println(num / count); • ANS: ArithmeticException
(Manager is a subclass of an Employee class) Employee worker1 = new Employee( ); System.out.println((Manager)worker1);
(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
int[ ] anArray = new int[10]; anArray[11] = o;
int[ ] anArray = new int[10]; anArray[11] = o; • ANS: ArrayIndexOutOfBoundsException
String s = “string”; System.out.println(s.substring(0,8));
String s = “string”; System.out.println(s.substring(0,8)); • ANS: StringIndexOutOfBOundsException
(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( ) );
(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
The for loop iterator traverses the entire array so the final output asks for the next element in the ArrayList that does not exist
Manager worker1 = null; String temp = worker1.getName( );
Manager worler1 = null; String temp = worker1.getName( ); • ANS: NullPointerException;
int units = Integer.parseInt(“1234a”); System.out.println(units + 1);
int units = Integer.parseInt(“1234a”); System.out.println(units + 1); • ANS: NumberFormatException as “1234a” is not a valid number
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
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
if (withDrawAmount > balance) { IllegalArgumentException exception = new IllegalArgumentException(“Amount exceeds Balance”); throw exception; } else balance -= wothDrawAmount;
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
Students must be able to THROW exceptions: if (radius < 0) throw new IllegalArgumentException (“bad radius value”); else I = Math.Pi * r * r;
Unchecked errors do not require try / catch • The exceptions students will be required to throw are: • IllegalArgumentException • IllegalStateException • NoSuchElementException