Java Exception Handling PDF
Document Details
Uploaded by SteadyCarolingianArt5561
Tags
Summary
These are lecture notes on exception handling in Java. They cover various exception types and how to handle them, including examples of divide by zero errors and InputMismatchExceptions.
Full Transcript
Java™ How to Program, 10/e Late Objects Version © Copyright 1992-2015 by Pearson Education, Inc. All Rights Reserved. 1 The content is mainly selected (sometimes modified) from the original slides provided by the authors of the textbook...
Java™ How to Program, 10/e Late Objects Version © Copyright 1992-2015 by Pearson Education, Inc. All Rights Reserved. 1 The content is mainly selected (sometimes modified) from the original slides provided by the authors of the textbook Readings Chapter 11: Exception Handling: A Deeper Look © Copyright 1992-2015 by Pearson Education, Inc. All Rights Reserved. 2 11.1 Introduction 11.2 Example: Divide by Zero without Exception Handling 11.3 Example: Handling ArithmeticExceptions and InputMismatchExceptions 11.4 When to Use Exception Handling 11.5 Java Exception Hierarchy 11.6 finally Block 11.7 Stack Unwinding and Obtaining Information from an Exception Object 11.8 Chained Exceptions 11.9 Declaring New Exception Types 11.10 Preconditions and Postconditions 11.11 Assertions © Copyright 1992-2015 by Pearson Education, Inc. All Rights Reserved. 3 Exception handling Exception: It is an indication of a problem that occurs during a program’s execution. The name “exception” implies that the problem occurs infrequently. With exception handling: A program can continue executing (rather than terminating) after dealing with a problem. Robust and fault-tolerant programs (i.e., programs that can deal with problems as they arise and continue executing). © Copyright 1992-2015 by Pearson Education, Inc. All Rights Reserved. 4 Some examples of Java Exceptions are: ArrayIndexOutOfBoundsException: occurs when an array has been accessed with an index that is negative or more than or equal to the size of array itself. ClassCastException occurs when an attempt is made to cast an object that does not have an is-a relationship with the type specified in the cast operator. A NullPointerException occurs when a null reference is used where an object is expected. Note: Only classes that extend Throwable (package java.lang) directly or indirectly can be used with exception handling. © Copyright 1992-2015 by Pearson Education, Inc. All Rights Reserved. 5 © Copyright 1992-2015 by Pearson Education, Inc. All Rights Reserved. 6 Exceptions are thrown (i.e., the exception occurs) by a method detects a problem and is unable to handle it. Stack trace—information displayed when an exception occurs and is not handled. Such Information includes: The name of the exception in a descriptive message that indicates the problem that occurred The method-call stack (i.e., the call chain) at the time it occurred. Represents the path of execution that led to the exception method by method. This information helps you debug the program. © Copyright 1992-2015 by Pearson Education, Inc. All Rights Reserved. 7 Java does not allow division by zero in integer arithmetic. Throws an ArithmeticException. Can arise from a several problems, so an error message (e.g., “/ by zero”) provides more specific information. Also, Java does allow division by zero with floating-point values. Such a calculation results in the value positive or negative infinity Floating-point value that displays as Infinity or -Infinity. If 0.0 is divided by 0.0, the result is NaN (not a number), which is represented as a floating-point value that displays as NaN. © Copyright 1992-2015 by Pearson Education, Inc. All Rights Reserved. 8 © Copyright 1992-2015 by Pearson Education, Inc. All Rights Reserved. 9 © Copyright 1992-2015 by Pearson Education, Inc. All Rights Reserved. 10 Last line of the stack trace started the call chain. Each line contains the class name and method followed by the filename and line number. The top row of the call chain indicates the throw point—the initial point at which the exception occurred. An InputMismatchException occurs when Scanner method nextInt receives a String that does not represent a valid integer. © Copyright 1992-2015 by Pearson Education, Inc. All Rights Reserved. 11 The application in Fig. 11.2 uses exception handling to process any ArithmeticExceptions and InputMistmatchExceptions that arise./ If the user makes a mistake, then the program catches and handles (i.e., deals with) the exception—in this case, allowing the user to try to enter the input. © Copyright 1992-2015 by Pearson Education, Inc. All Rights Reserved. 12 © Copyright 1992-2015 by Pearson Education, Inc. All Rights Reserved. 13 © Copyright 1992-2015 by Pearson Education, Inc. All Rights Reserved. 14 © Copyright 1992-2015 by Pearson Education, Inc. All Rights Reserved. 15 try block encloses a code that might throw an exception or code that should not execute if an exception occurs. Consists of the keyword try followed by a block of code enclosed in curly braces. catch block (also called a catch clause or exception handler) catches and handles an exception. Consists of the keyword catch followed by an exception parameter in parentheses and a block of code enclosed in curly braces. The exception parameter identifies the exception type that the handler can process. The parameter’s name enables the catch block to interact with a caught exception object. © Copyright 1992-2015 by Pearson Education, Inc. All Rights Reserved. 16 At least one catch block or a finally block (Section 11.6) must immediately follow the try block. The try block and its corresponding catch and/or finally blocks form a try statement. When an exception occurs in a try block, the try block terminates immediately and the catch block that executes is the first one whose type matches the type of the exception that occurred. Use the System.err (standard error stream) object to output error messages. By default, displays data to the command prompt. © Copyright 1992-2015 by Pearson Education, Inc. All Rights Reserved. 17 Multi-catch If the bodies of several catch blocks are identical, you can use the multi-catch feature (introduced in Java SE 7) to catch those exception types in a single catch handler and perform the same task. The syntax for a multi-catch is: catch (Type1 | Type2 | Type3 e) Each exception type is separated from the next with a vertical bar (|). The preceding line of code indicates that any of the types (or their subclasses) can be caught in the exception handler. Any number of Throwable types can be specified in a multi-catch. © Copyright 1992-2015 by Pearson Education, Inc. All Rights Reserved. 18 Uncaught exception—one for which there are no matching catch blocks. Recall that previous uncaught exceptions caused the application to terminate early. After the exception is handled: control resumes after the last catch block. If no exceptions are thrown in a try block, the catch blocks are skipped and control continues with the first statement after the catch blocks © Copyright 1992-2015 by Pearson Education, Inc. All Rights Reserved. 19 When a try block terminates, local variables declared in the block go out of scope. The local variables of a try block are not accessible in the corresponding catch blocks. When a catch block terminates, local variables declared within the catch block (including the exception parameter) also go out of scope. When a method throws an exception, the method terminates and does not return a value, and its local variables go out of scope. If the local variables were references to objects and there were no other references to those objects, the objects would be available for garbage collection. © Copyright 1992-2015 by Pearson Education, Inc. All Rights Reserved. 20 throws clause—specifies the exceptions that a method might throw if problems occur. Must appear after the method’s parameter list and before the body. Contains a comma-separated list of the exception types. May be thrown by statements in the method’s body or by methods called from there. Clients of a method with a throws clause are thus informed that the method might throw exceptions. © Copyright 1992-2015 by Pearson Education, Inc. All Rights Reserved. 21 Exception handling is designed to process synchronous errors, which occur when a statement executes. out-of-range array indices arithmetic overflow division by zero invalid method parameters Exception handling is not designed to process problems associated with asynchronous events disk I/O completions network message arrivals mouse clicks and keystrokes © Copyright 1992-2015 by Pearson Education, Inc. All Rights Reserved. 22 Class Throwable has two subclasses: Exception and Error. Figure 11.3 shows a small portion of the inheritance hierarchy for class Throwable (a subclass of Object). Only Throwable objects can be used with the exception-handling mechanism. Exception classes inherit directly or indirectly from class Exception, forming an inheritance hierarchy. You can extend this hierarchy with your own exception classes. Class Exception and its subclasses represent exceptional situations that can occur in a Java program These can be caught and handled by the application. Class Error and its subclasses represent abnormal situations happen in JVM. Errors happen infrequently. These should not be caught by applications. Applications usually cannot recover from Errors. © Copyright 1992-2015 by Pearson Education, Inc. All Rights Reserved. 23 © Copyright 1992-2015 by Pearson Education, Inc. All Rights Reserved. 24 Unchecked exceptions: It includes direct or indirect subclasses of class RuntimeException (package java.lang). Typically caused by defects in your program’s code, e.g.: ArrayIndexOutOfBoundsExceptions, ArithmeticExceptions Checked exceptions: It includes all subclasses of Exception but not RuntimeException. Caused by conditions that are not in the control of the program—e.g., in file processing, the program can’t open a file if it does not exist. Compiler enforces a catch-or-declare requirement for checked exceptions only. catch-or-declare requirement: the compiler verifies that the checked exception (or one of its superclasses) is caught (using try/catch) or is declared in a throws clause, otherwise compiler will issue an error message. © Copyright 1992-2015 by Pearson Education, Inc. All Rights Reserved. 25 © Copyright 1992-2015 by Pearson Education, Inc. All Rights Reserved. 26 If a catch handler is written to catch superclass exception objects, then it can also catch all objects of that class’s subclasses. This enables catch to handle related exceptions polymorphically. You can catch each subclass individually if those exceptions require different processing. If multiple catch blocks match a particular exception type, then only the first matching catch block executes. It’s a compilation error to catch the exact same type in two different catch blocks associated with a particular try block. © Copyright 1992-2015 by Pearson Education, Inc. All Rights Reserved. 27 © Copyright 1992-2015 by Pearson Education, Inc. All Rights Reserved. 28 The finally block (follows the try block or the catch block) which consists of the finally keyword, followed by code enclosed in curly braces, also known as finally clause. finally block will execute: whether or not an exception is thrown in the corresponding try block. if a try block exits by using a return or by reaching its closing right brace. whether or not an exception is thrown in a catch block. finally block will not execute if the application exits early from a try block by calling method System.exit. © Copyright 1992-2015 by Pearson Education, Inc. All Rights Reserved. 29 Because a finally block always executes, so it typically contains resource-release code. Programs that obtain certain resources must return them to the system to avoid so-called resource leaks. Java automatically garbage collects memory no longer used by programs, thus avoiding most memory leaks. Other types of resource leaks can occur. Files, database connections and network connections that are not closed properly might not be available for use in other programs. © Copyright 1992-2015 by Pearson Education, Inc. All Rights Reserved. 30 © Copyright 1992-2015 by Pearson Education, Inc. All Rights Reserved. 31 © Copyright 1992-2015 by Pearson Education, Inc. All Rights Reserved. 32 © Copyright 1992-2015 by Pearson Education, Inc. All Rights Reserved. 33 If an exception that occurs in a try block cannot be caught by one of that try block’s catch handlers, control proceeds to the finally block. Then the program passes the exception to the next outer try block— normally in the calling method—where an associated catch block might catch it. This process can occur through many levels of try blocks. The exception could go uncaught. © Copyright 1992-2015 by Pearson Education, Inc. All Rights Reserved. 34 throw statement—indicates that an exception has occurred. Used to throw exceptions. Indicates to client code that an error has occurred. Specifies an object to be thrown. The operand of a throw can be of any class derived from class Throwable. © Copyright 1992-2015 by Pearson Education, Inc. All Rights Reserved. 35 Rethrow an exception Done when a catch block cannot process that exception or can only partially process it. Defers the exception handling (or perhaps a portion of it) to another catch block associated with an outer try statement. Rethrow uses the throw keyword, followed by a reference to the exception object that was just caught. When a rethrow occurs, the next enclosing try block detects the exception, and that try block’s catch blocks attempt to handle it. © Copyright 1992-2015 by Pearson Education, Inc. All Rights Reserved. 36 © Copyright 1992-2015 by Pearson Education, Inc. All Rights Reserved. 37 Stack unwinding—When an exception is thrown but not caught in a particular scope, the method-call stack is “unwound” An attempt is made to catch the exception in the next outer try block. All local variables in the unwound method go out of scope and control returns to the statement that originally invoked that method. If a try block encloses that statement, an attempt is made to catch the exception. If a try block does not enclose that statement or if the exception is not caught, then stack unwinding occurs again. © Copyright 1992-2015 by Pearson Education, Inc. All Rights Reserved. 38 © Copyright 1992-2015 by Pearson Education, Inc. All Rights Reserved. 39 © Copyright 1992-2015 by Pearson Education, Inc. All Rights Reserved. 40 © Copyright 1992-2015 by Pearson Education, Inc. All Rights Reserved. 41 © Copyright 1992-2015 by Pearson Education, Inc. All Rights Reserved. 42 Sometimes a method responds to an exception by throwing a different exception type that is specific to the current application. If a catch block throws a new exception, the original exception’s information and stack trace are lost. Earlier Java versions provided no mechanism to wrap the original exception information with the new exception’s information. This made debugging such problems particularly difficult. Chained exceptions enable an exception object to maintain the complete stack-trace information from the original exception. © Copyright 1992-2015 by Pearson Education, Inc. All Rights Reserved. 43 © Copyright 1992-2015 by Pearson Education, Inc. All Rights Reserved. 44 © Copyright 1992-2015 by Pearson Education, Inc. All Rights Reserved. 45 © Copyright 1992-2015 by Pearson Education, Inc. All Rights Reserved. 46 Sometimes it’s useful to declare your own exception classes that are specific to the problems that can occur when another programmer uses your reusable classes. A new exception class must extend an existing exception class to ensure that the class can be used with the exception-handling mechanism. A typical new exception class contains constructors and overrides toString method. The following example demonstrate a user defined exception (https://www.slideshare.net/talhaijaz2/lecture-22-55803418) © Copyright 1992-2015 by Pearson Education, Inc. All Rights Reserved. 47 © Copyright 1992-2015 by Pearson Education, Inc. All Rights Reserved. 48 © Copyright 1992-2015 by Pearson Education, Inc. All Rights Reserved. 49 run: Depositing $500... Withdrawing $100... Withdrawing $600... Sorry, but you are short $200.0 InsufficientFundsException at CheckingAccount.withdraw(CheckingAccount.java:19) at BankDemo.main(BankDemo.java:11) © Copyright 1992-2015 by Pearson Education, Inc. All Rights Reserved. 50 Programmers spend significant amounts of time maintaining and debugging code. To facilitate these tasks and to improve the overall design, they can specify the expected states before and after a method’s execution. These states are called preconditions and postconditions, respectively. When preconditions or postconditions are not met, methods typically throw exceptions. © Copyright 1992-2015 by Pearson Education, Inc. All Rights Reserved. 51 A precondition must be true when a method is invoked. Describes constraints on method parameters and any other expectations the method has about the current state of a program just before it begins executing. A postcondition is true after the method successfully returns. Describes constraints on the return value and any other side effects the method may have. When writing your own method, document all postconditions so that others know what to expect when they call your method, and you should make certain that your method honors all its postconditions if its preconditions are met. © Copyright 1992-2015 by Pearson Education, Inc. All Rights Reserved. 52 As an example, examine String method charAt, which has one int parameter—an index in the String. For a precondition, method charAt assumes that index is greater than or equal to zero and less than the length of the String. If the precondition is met, the postcondition states that the method will return the character at the position in the String specified by the parameter index. Otherwise, the method throws an IndexOutOfBounds- Exception. We trust that method charAt satisfies its postcondition, provided that we meet the precondition. © Copyright 1992-2015 by Pearson Education, Inc. All Rights Reserved. 53 When implementing and debugging a class, it’s sometimes useful to state conditions that should be true at a particular point in a method. Assertions help ensure a program’s validity by catching potential bugs and identifying possible logic errors during development. Preconditions and postconditions are two types of assertions. © Copyright 1992-2015 by Pearson Education, Inc. All Rights Reserved. 54 Java includes two versions of the assert statement for validating assertions programatically. assert evaluates a boolean expression and, if false, throws an AssertionError (a subclass of Error). assert expression; throws an AssertionError if expression is false. assert expression1 : expression2; evaluates expression1 and throws an AssertionError with expression2 as the error message if expression1 is false. Can be used to programmatically implement preconditions and postconditions or to verify any other intermediate states that help you ensure your code is working correctly. © Copyright 1992-2015 by Pearson Education, Inc. All Rights Reserved. 55 You use assertions primarily for debugging and identifying logic errors in an application. You must explicitly enable assertions when executing a program They reduce performance. They are unnecessary for the program’s user. To enable assertions, use the java command’s -ea command-line option, as in java -ea AssertTest © Copyright 1992-2015 by Pearson Education, Inc. All Rights Reserved. 56 © Copyright 1992-2015 by Pearson Education, Inc. All Rights Reserved. 57 © Copyright 1992-2015 by Pearson Education, Inc. All Rights Reserved. 58