1 / 61

Exception Handling

Exception Handling. Starring: ArrayIndexOutOfBOunds Co-Starring: Ariane Rocket IOException RunTImeException. Purpose: In this lecture series we will learn about Exception Handling.

tress
Télécharger la présentation

Exception Handling

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  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.

  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

  4. Resources: • Barrons: • Page 15-16 • Pages 41, 79, 170, 180, 250, 252, 255, 375

  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

  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

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

  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

  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

  10. Exceptions are divided into two categories: • Exceptions that Java REQUIRES the programmer to handle IOException is one that MUST be handled

  11. Exceptions that the programmer has the option of handling ArithmeticException ArrayIndexOutOfBoundsException

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

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

  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

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

  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)

  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

  18. 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 --"); }

  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

  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

  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

  22. Unchecked Exceptions: • RunTime Exceptions can occur almost anywhere • These kind of errors are the programmers fault !!! • Unchecked exceptions halt the program

  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

  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:

  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

  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)

  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)

  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

  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

  30. In these Examples of Exceptions, what type of exception would occur ? int num = 21; int count = 0; System.out.println(num / count);

  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

  32. (Manager is a subclass of an Employee class) Employee worker1 = new Employee( ); System.out.println((Manager)worker1);

  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

  34. int[ ] anArray = new int[10]; anArray[11] = o;

  35. int[ ] anArray = new int[10]; anArray[11] = o; • ANS: ArrayIndexOutOfBoundsException

  36. String s = “string”; System.out.println(s.substring(0,8));

  37. String s = “string”; System.out.println(s.substring(0,8)); • ANS: StringIndexOutOfBOundsException

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

  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

  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

  41. Manager worker1 = null; String temp = worker1.getName( );

  42. Manager worler1 = null; String temp = worker1.getName( ); • ANS: NullPointerException;

  43. int units = Integer.parseInt(“1234a”); System.out.println(units + 1);

  44. int units = Integer.parseInt(“1234a”); System.out.println(units + 1); • ANS: NumberFormatException as “1234a” is not a valid number

  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

  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

  47. if (withDrawAmount > balance) { IllegalArgumentException exception = new IllegalArgumentException(“Amount exceeds Balance”); throw exception; } else balance -= wothDrawAmount;

  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

  49. Students must be able to THROW exceptions: if (radius < 0) throw new IllegalArgumentException (“bad radius value”); else I = Math.Pi * r * r;

  50. Unchecked errors do not require try / catch • The exceptions students will be required to throw are: • IllegalArgumentException • IllegalStateException • NoSuchElementException

More Related