Presentation is loading. Please wait.

Presentation is loading. Please wait.

Chapter 81 Exception Handling Chapter 8. 2 Objectives become familiar with the notion of exception handling learn Java syntax for exception handling learn.

Similar presentations


Presentation on theme: "Chapter 81 Exception Handling Chapter 8. 2 Objectives become familiar with the notion of exception handling learn Java syntax for exception handling learn."— Presentation transcript:

1 Chapter 81 Exception Handling Chapter 8

2 2 Objectives become familiar with the notion of exception handling learn Java syntax for exception handling learn to use exception handling effectively in classes and programs

3 Chapter 83 Outline Basic Exception Handling Defining Exception Classes Using Exception Classes (optional) Graphics Supplement

4 Chapter 84 Introduction A program can be written assuming that nothing unusual or incorrect will happen. –The user will always enter an integer when prompted to do so. –There will always be a nonempty list for a program that takes an entry from the list. –The file containing the needed information will always exist. Unfortunately, it isn’t always so.

5 Chapter 85 Introduction, cont. Once the core program is written for the usual, expected case(s), Java’s exception- handling facilities should be added to accommodate the unusual, unexpected case(s).

6 Chapter 86 Introduction, cont. Exception handling divides a class or method definition into separate sections: –one section for the normal case(s) –another section for the exceptional case(s). Depending on how a method is used, special cases may need to be handled in different ways. Sometimes an exception needs to be thrown to handle a problem outside the method.

7 Chapter 87 Basic Exception Handling: Outline Exceptions in Java Predefined Exception Classes

8 Chapter 88 Exception Handling Either your code or Java signals when something unusual happens. The signaling process is called throwing an exception. Somewhere in your program, you can place code to handle the exception.

9 Chapter 89 Exceptions in Java: Example simple example –Suppose the students are hosting an event to express appreciation to their professor, at which donuts and milk will be served. –If the number of donuts is known, and the number of glasses of milk is known, it should be possible to calculate the number of donuts per glass of milk.

10 Chapter 810 Exceptions in Java: Example, cont. simple example, cont. –But what if there is no milk? –An attempt to divide the number of donuts by the number of glasses of milk will result in an attempt to divide by zero. –This would be an utter (udder?) disaster, known in Java as an exception.

11 Chapter 811 Exceptions in Java: Example, cont. In Java, it is possible to test for this unusual situation using an if-else statement, for example.

12 Chapter 812 Exceptions in Java: Example, cont. class GotMilk

13 Chapter 813 Exceptions in Java: Example, cont.

14 Chapter 814 Exceptions in Java: Example, cont. In Java, it is also possible to throw an exception.

15 Chapter 815 Exceptions in Java: Example, cont. class ExceptionDemo

16 Chapter 816 Exceptions in Java: Example, cont.

17 Chapter 817 Exceptions in Java: Example, cont.

18 Chapter 818 Exceptions in Java Exceptions are handled using a try-throw- catch threesome. try block syntax try { Code_to_Try Throw_An_Exception_Or_Invoke_A_Method _That_Might_Throw_An_Exception Possibly_More_Code }

19 Chapter 819 Exceptions in Java, cont. Exception is a predefined class. The throw statement creates a new object of the class Exception and throws it. throw new Exception (“Exception: No Milk!”); When an exception is thrown, control transfers from the try block to a catch block, and is called catching the exception.

20 Chapter 820 throw Statement and catch Block throw statement syntax throw new Exception_Class_Name (Quoted_String_Argument); –Quoted_String_Argument is passed to the constructor for class Exception which stores it in the instance variable of the Exception object.

21 Chapter 821 throw Statement and catch Block, cont. catch block syntax catch(Exception e) { Code_To_Be_Performed { –e is called the catch -block parameter.

22 Chapter 822 The catch Block The class name preceding the catch -block parameter specifies what kind of exception the catch block can catch. –Class name Exception permits any exception to be caught. The catch -block parameter provides a name for the exception that is caught, to permit the exception object to be used subsequently.

23 Chapter 823 The catch Block, cont. If the program cannot recover from the exception, the catch block can include System.exit(0);

24 Chapter 824 method getMessage Every exception has a method called getMessage. By default, this method retrieves the string given to the constructor of the Exception object.

25 Chapter 825 method getMessage, cont. class ExceptionDemo Flow of Control - no exception is thrown

26 Chapter 826 method getMessage, cont. class ExceptionDemo Flow of Control - an exception is thrown

27 Chapter 827 try-throw-catch The try-throw-catch threesome is similar to an if-else statement. However, an object of the class Exception is created and its message can be carried by the thrown exception, providing more versatility than an if-else statement

28 Chapter 828 Predefined Exception Classes Some methods in predefined classes can throw predefined exceptions. An invocation of such a predefined method can be included in a try block and followed by a catch block. some predefined exceptions: –IOException –ClassNotFoundException –FileNotFoundException

29 Chapter 829 Predefined Exception Classes, cont. Class Exception is the root class of all exceptions. However, an exception typically is handled more appropriately by one of its descendants. The string returned by a predefined exception typically provides enough information to identify the reason for the exception.

30 Chapter 830 ArrayOutOfBoundsException When a program attempts to use an array index that is out of bounds, an ArrayOutOfBoundsException is thrown. The program ends unless the exception is caught in a catch block. An ArrayOutOfBoundsException usually indicates a code error rather than an exception that should be caught.

31 Chapter 831 Defining Exception Classes You can define your own exception classes, but they must be derived from an existing exception class. Constructors are the most important, and often the only methods (except for methods inherited from the base class).

32 Chapter 832 Defining Exception Classes, cont. class DivideByZeroException

33 Chapter 833 Defining Exception Classes, cont. class DivideByZeroExceptionDemo

34 Chapter 834 Defining Exception Classes, cont.

35 Chapter 835 Defining Exception Classes, cont.

36 Chapter 836 Defining Exception Classes, cont.

37 Chapter 837 Java Tip: Preserve getMessage For all predefined exception classes, method getMessage returns either –the string that is passed as an argument to the constructor or –a default string if no argument is passed to the constructor. The behavior of method getMessage should be preserved in any exception class you define.

38 Chapter 838 Java Tip: Preserve getMessage, cont. This is done by including a string parameter that begins with a call to super. public MyException(String message) { super(message); More_Code_If_Appropriate }

39 Chapter 839 Java Tip: Preserve getMessage, cont. Also include a default constructor. public MyException() { super(“MyException thrown”); More_Code_If_Appropriate }

40 Chapter 840 Programming Tip: When to Define an Exception Class In general, define an exception class if you are going to insert a throw statement in your code. This permits catch blocks to distinguish between your exceptions and exceptions thrown by predefined methods.

41 Chapter 841 Guidelines Use class Exception as the base class unless there is a compelling reason to do otherwise. Define at least two constructors. Typically, no other methods are needed. Begin each constructor definition with a call to the constructor of the base class.

42 Chapter 842 Guidelines, cont. Include a default constructor in which the call to super has a string argument indicating the kind of exception. –The string can be recovered using the getMessage method. Include a constructor that takes a single string argument used in the call to super. –The string can be recovered with a call to getMessage.

43 Chapter 843 Using Exception Classes: Outline Declaring Exceptions (Passing the Buck) Exceptions That Need Not Be Caught (optional) The AssertionError Class Multiple Throws and Catches (optional) The finally Block (optional) Rethrowing an Exception

44 Chapter 844 Declaring Exceptions (Passing the Buck) Sometimes is it appropriate to handle an exception other than in the method where the exception occurred. For example, it might be better to handle the exception in the method that called the method that called the method… that threw the exception

45 Chapter 845 Declaring Exceptions, cont. If a method can throw an exception but does not catch it, it must alert the programmer to the possibility of an exception by including a throws clause. Example public void someMethod() throws DivideByZeroException

46 Chapter 846 Accounting for Exceptions An exception can be caught in a catch block within a method definition. Alternatively, the possibility of an exception can be declared at the start of the method definition by placing the exception-class name in a throws clause. These two approaches can be mixed in a method, catching some exceptions and declaring others in a throws clause.

47 Chapter 847 Accounting for Exceptions, cont. If method_A uses a throws clause instead of handling an exception and method_B calls method_A, then method_B either must handle the exception or must also include a throws clause.

48 Chapter 848 Accounting for Exceptions, cont. class DoDivision

49 Chapter 849 Accounting for Exceptions, cont. A throws clause can include more than one exception type. example public int someMethod()throws IOException, DivideByZeroException

50 Chapter 850 Accounting for Exceptions, cont. Some method in the calling hierarchy should handle the exception. If an exception is thrown, but never caught, either the program terminates or its behavior becomes unreliable.

51 Chapter 851 Exceptions That Need Not Be Caught Some exceptions do not need to be accounted for in any way. –(Perhaps these are the exceptions that prove the rule about needing to account for exceptions.) Exceptions that do not need to be accounted for result from errors and usually are thrown by methods in predefined classes.

52 Chapter 852 Exceptions That Need Not Be Caught, cont. “Exceptions” that derive from the class Error or the class RunTimeException do not need to be accounted for. examples –NoSuchMethodError –OutOfMemoryError Adding a catch clause or “passing the buck” will not solve the problem.

53 Chapter 853 Exceptions That Need Not Be Caught, cont. In the event you fail to account for some exception that Java requires you to account for, the compiler will alert you.

54 Chapter 854 throws Clauses in Derived Classes When a method is redefined in a derived class, the redefined method cannot contain any exception classes that are not in the throws clause of the same method in the base class (though the derived class can list fewer exceptions in its throws clause). Any exceptions thrown in the derived class must be caught or thrown by the base class.

55 Chapter 855 (optional) The AssertionError Class If your program contains an assertion check and the assertion check fails, the program may terminate with an error message. –An “exception” of the class AssertionError is thrown. –If it is not caught in a catch block (which is typical), the program will terminate.

56 Chapter 856 Multiple Throws and Catches A try block can throw any number of different types of exceptions. Each catch block can catch only one type of exception. Multiple catch blocks after a try block can catch multiple types of exceptions.

57 Chapter 857 Multiple Throws and Catches, cont. class TwoCatchesDemo

58 Chapter 858 Multiple Throws and Catches, cont.

59 Chapter 859 Multiple Throws and Catches, cont.

60 Chapter 860 Multiple Throws and Catches, cont.

61 Chapter 861 Multiple Throws and Catches, cont. class NegativeNumbersException

62 Chapter 862 Java Tip: Catch the More Specific Exceptions First catch blocks are examined in order. The first matching catch block is executed. More specific exceptions should precede less specific exceptions, i.e. exceptions lower in the exception hierarchy should come before exceptions higher in the exception hierarchy.

63 Chapter 863 Programming Tip: Exception Handling and Information Hiding A method invocation can throw an exception that is declared in its throws clause. But, it does not matter where in the method definition the throw statement is located. The fact that it might throw an exception is all that matters.

64 Chapter 864 Keep It Simple Attempt to modify a program or class definition so that it does not need a throw statement. In general, use exceptions sparingly. If the way the exception is handled depends on the calling method, let the calling method handle the exception. Consider throwing the exception and catching the exception in separate methods.

65 Chapter 865 Keep It Simple, cont. public void methodB() {... try {... methodA();... } catch (MyException e)...

66 Chapter 866 Nested try-catch Blocks Inner try-catch blocks should be placed inside a method definition, with the method invocation in an outer try-catch block. If an inner try-catch block is placed inside an outer try-catch block, the catch -block parameters in the inner and outer blocks must have different names.

67 Chapter 867 Nested try-catch Blocks, cont. If an inner try block and its catch block are placed inside an outer try block and an exception is thrown in the inner try block, but not caught by the inner catch block, the exception is propagated to the outer try block and might be caught by an outer catch block.

68 Chapter 868 (optional) The finally Block A finally block can be added after a try block and its catch blocks. The finally block is executed –if the try block throws no exceptions –if the try block throws an exception which is caught by a catch block –if an exception is thrown but not caught i.e. it is always executed.

69 Chapter 869 The finally Block, cont. syntax try { … } catch Block(s) finally { … }

70 Chapter 870 (optional) Rethrowing an Exception An exception can be thrown within a catch block for handling further up the method-call chain.

71 Chapter 871 Case Study: A Line-Oriented Calculator Write a program that behaves like a simple, hand-held calculator which does addition, subtraction, multiplication, and division. It does simple line-by-line text input and output. Each operation is on a line by itself. A session ends when the user enters E or e.

72 Chapter 872 Case Study: A Line-Oriented Calculator, cont. sample dialog result = 0 + 80 result + 80 = 80 updated result = 80 -2 result - 2 = 78 updated result = 78

73 Chapter 873 Case Study: A Line-Oriented Calculator, cont. The current result is stored in a private instance variable called result. Method reset will reset result to zero. Method evaluate will calculate the result of one operation. Method getResult will access the value of result.

74 Chapter 874 Case Study: A Line-Oriented Calculator, cont. Method setResult will set the value of result to any specified value. Method doCalculation will include a loop to do a series of operations, with a call to evaluate during each loop iteration. An exception will be thrown if the user attempts to divide by zero.

75 Chapter 875 Case Study: A Line-Oriented Calculator, cont. If doubles are used, the == operator cannot be used to test for exact equality. –A DivideByZeroException should be thrown for is an attempt is made to divide by a number “very close to zero.” An UnknownOpException will be thrown if the user specifies an unknown operation.

76 Chapter 876 Case Study: A Line-Oriented Calculator, cont. class UnknownOpException

77 Chapter 877 Case Study: A Line-Oriented Calculator, cont. A preliminary version of the program is produced to test and debug the unexceptional behavior of the program.

78 Chapter 878 Case Study: A Line-Oriented Calculator, cont. class PrelimCalculator

79 Chapter 879 Case Study: A Line-Oriented Calculator, cont. class PrelimCalculator, contd.

80 Chapter 880 Case Study: A Line-Oriented Calculator, cont.

81 Chapter 881 Case Study: A Line-Oriented Calculator, cont. There are three places to catch an exception thrown by method evaluate : –in method evaluate or in method doCalculation if you want the user to reenter the operator –in method main if you want to restart the calculation. The choice is to restart the calculation.

82 Chapter 882 Case Study: A Line-Oriented Calculator, cont. class Calculator

83 Chapter 883 Case Study: A Line-Oriented Calculator, cont. class Calculator, contd.

84 Chapter 884 Case Study: A Line-Oriented Calculator, cont. class Calculator, contd.

85 Chapter 885 Case Study: A Line-Oriented Calculator, cont.

86 Chapter 886 Graphics Supplement: Exceptions in GUIs An uncaught exception in a (non-GUI) application will end the program. An uncaught exception in a GUI program (either a JFrame GUI or an applet) will not end the program. –However, unless the exception is caught, the GUI may not cope correctly with the exception or the user may receive insufficient instructions.

87 Chapter 887 Programming Example: A JFrame Using Exceptions The example JFrame GUI allows the user to write the name of a color in a text field and to click the “Show Color” button. –If the GUI recognizes the color, the background color changes to the named color. –Otherwise, the text field displays “Unknown Color” and the background changes to gray.

88 Chapter 888 Programming Example: A JFrame Using Exceptions, cont. class ColorDemo

89 Chapter 889 class UnknownColorException Programming Example: A JFrame Using Exceptions, cont.

90 Chapter 890 class ShowColorDemo Programming Example: A JFrame Using Exceptions, cont.

91 Chapter 891 Programming Example: A JFrame Using Exceptions, cont.

92 Chapter 892 throws Clause Not Allowed in actionPerformed A throws clause cannot be added to method actionPerformed in any action listener class. Any exception thrown in method actionPerformed must be caught in method actionPerformed. Similarly, if method windowClosing is redefined in a window listener class, you may not add a throws clause to method windowClosing.

93 Chapter 893 Summary You have become familiar with the notion of exception handling. You have learned Java syntax for exception handling. You have learned to use exception handling effectively in classes and programs.


Download ppt "Chapter 81 Exception Handling Chapter 8. 2 Objectives become familiar with the notion of exception handling learn Java syntax for exception handling learn."

Similar presentations


Ads by Google