Exception Handling Introduction. Error-Prevention Tip 13.1 OBJECTIVES

Similar documents
Assoc. Prof. Marenglen Biba. (C) 2010 Pearson Education, Inc. All rights reserved.

Exception Handling Pearson Education, Inc. All rights reserved.

Exception Handling in C++

Program Correctness and Efficiency. Chapter 2

Exception Handling Pearson Education, Inc. All rights reserved.

Object Oriented Programming

Data Structures. 02 Exception Handling

Lecture 20. Java Exceptional Event Handling. Dr. Martin O Connor CA166

Object oriented programming. Instructor: Masoud Asghari Web page: Ch: 7

Comp 249 Programming Methodology Chapter 9 Exception Handling

Exception-Handling Overview

AP COMPUTER SCIENCE JAVA CONCEPTS IV: RESERVED WORDS

Java How to Program, 10/e. Copyright by Pearson Education, Inc. All Rights Reserved.

! Errors can be dealt with at place error occurs

Programming II (CS300)

BBM 102 Introduction to Programming II Spring Exceptions

Java Loose Ends. 11 December 2017 OSU CSE 1

Internal Classes and Exceptions

BBM 102 Introduction to Programming II Spring 2017

Programming II (CS300)

Le L c e t c ur u e e 5 To T p o i p c i s c t o o b e b e co c v o e v r e ed e Exception Handling

Java Fundamentals p. 1 The Origins of Java p. 2 How Java Relates to C and C++ p. 3 How Java Relates to C# p. 4 Java's Contribution to the Internet p.

A Third Look At Java. Chapter Seventeen Modern Programming Languages, 2nd ed. 1

Exception Handling. Chapter 9

Exceptions. References. Exceptions. Exceptional Conditions. CSE 413, Autumn 2005 Programming Languages

IS 0020 Program Design and Software Tools

Chapter 5 Object-Oriented Programming

EXCEPTION HANDLING. Summer 2018

DOWNLOAD PDF CORE JAVA APTITUDE QUESTIONS AND ANSWERS

Std 12 Lesson-10 Exception Handling in Java ( 1

Exceptions. What exceptional things might our programs run in to?

Programming Languages Third Edition. Chapter 9 Control I Expressions and Statements

ECE 122. Engineering Problem Solving with Java

Objectives for this class meeting. 1. Conduct review of core concepts concerning contracts and pre/post conditions

CS 3 Introduction to Software Engineering. 3: Exceptions

Absolute C++ Walter Savitch

Exceptions. Computer Science and Engineering College of Engineering The Ohio State University. Lecture 15

Object-Oriented Programming

CS313D: ADVANCED PROGRAMMING LANGUAGE

JAVA CONCEPTS Early Objects

Chapter 9. Exception Handling. Copyright 2016 Pearson Inc. All rights reserved.

Index. Index. More information. block statements 66 y 107 Boolean 107 break 55, 68 built-in types 107

Correctness and Robustness

Day 8. COMP1006/1406 Summer M. Jason Hinek Carleton University

Exception Handling. Sometimes when the computer tries to execute a statement something goes wrong:

Pages and 68 in [JN] conventions for using exceptions in Java. Chapter 8 in [EJ] guidelines for more effective use of exceptions.

Sri Vidya College of Engineering & Technology Question Bank

Assertions and Exceptions Lecture 11 Fall 2005

Exception Handling. Run-time Errors. Methods Failure. Sometimes when the computer tries to execute a statement something goes wrong:

A Short Summary of Javali

Java for Programmers Course (equivalent to SL 275) 36 Contact Hours

Object Oriented Programming

National University. Faculty of Computer Since and Technology Object Oriented Programming

Exceptions. CSE 142, Summer 2002 Computer Programming 1.

Exceptions. Readings and References. Exceptions. Exceptional Conditions. Reading. CSE 142, Summer 2002 Computer Programming 1.

Object Oriented Programming Exception Handling

1 Shyam sir JAVA Notes

Chapter 13 Exception Handling

Weiss Chapter 1 terminology (parenthesized numbers are page numbers)

COMP 213. Advanced Object-oriented Programming. Lecture 17. Exceptions

6.Introducing Classes 9. Exceptions

WA1278 Introduction to Java Using Eclipse

Preconditions. CMSC 330: Organization of Programming Languages. Signaling Errors. Dealing with Errors

COMP1008 Exceptions. Runtime Error

CSE 331 Software Design & Implementation

UNIT 3 ARRAYS, RECURSION, AND COMPLEXITY CHAPTER 11 CLASSES CONTINUED

Chapter 10 Classes Continued. Fundamentals of Java

Reminder. Topics CSE What Are Exceptions?! Lecture 11 Exception Handling

VALLIAMMAI ENGINEERING COLLEGE

Exceptions Chapter 10. Instructor: Scott Kristjanson CMPT 125/125 SFU Burnaby, Fall 2013

Exceptions, try - catch - finally, throws keyword. JAVA Standard Edition

Exceptions in Java

Data Structures and Algorithms Design Goals Implementation Goals Design Principles Design Techniques. Version 03.s 2-1

Advanced Flow of Control -- Introduction

Checked and Unchecked Exceptions in Java

JAVA BASICS II. Example: FIFO

Exceptions. Produced by. Algorithms. Eamonn de Leastar Department of Computing, Maths & Physics Waterford Institute of Technology

CSC System Development with Java. Exception Handling. Department of Statistics and Computer Science. Budditha Hettige

14. Exception Handling

Exception Handling. Chapter 11. Outline. Example: The Quotient app What Are Exceptions? Java By Abstraction Chapter 11

Core Java - SCJP. Q2Technologies, Rajajinagar. Course content

Exceptions and assertions

Unit III Rupali Sherekar 2017

Administration. Exceptions. Leftovers. Agenda. When Things Go Wrong. Handling Errors. CS 99 Summer 2000 Michael Clarkson Lecture 11

17. Handling Runtime Problems

CS 251 Intermediate Programming Exceptions

Chapter 11 Handling Exceptions and Events. Chapter Objectives

Get Unique study materials from

CS313D: ADVANCED PROGRAMMING LANGUAGE

Introduction to Software Design

About This Lecture. Outline. Handling Unusual Situations. Reacting to errors. Exceptions

Exceptions. Examples of code which shows the syntax and all that

Chapter 4: Control Structures I (Selection) Objectives. Objectives (cont d.) Control Structures. Control Structures (cont d.

Problem Solving with C++

Introduction to C++ Programming Pearson Education, Inc. All rights reserved.

Chapter 4 Defining Classes I

Course Description. Learn To: : Intro to JAVA SE7 and Programming using JAVA SE7. Course Outline ::

Contents. Figures. Tables. Examples. Foreword. Preface. 1 Basics of Java Programming 1. xix. xxi. xxiii. xxvii. xxix

Chapter 12 Exception Handling

Safety SPL/2010 SPL/20 1

Transcription:

1 2 13 Exception Handling It is common sense to take a method and try it. If it fails, admit it frankly and try another. But above all, try something. Franklin Delano Roosevelt O throw away the worser part of it, And live the purer with the other half. William Shakespeare If they re running and they don t look where they re going I have to come out from somewhere and catch them. Jerome David Salinger O infinite virtue com st thou smiling from the world s great snare uncaught? William Shakespeare 1992-2007 Pearson Education Inc. All rights reserved. OBJECTIVES In this chapter you will learn: How exception and error handling works. To use, and to detect, indicate and handle exceptions, respectively. To use the block to release resources. How stack unwinding enables exceptions not caught in one scope to be caught in another scope. How stack traces help in debugging. How exceptions are arranged in an exception class hierarchy. To declare new exception classes. To create chained exceptions that maintain complete stack trace information. 3 13.1 Introduction 13.2 Exception-Handling Overview 13.3 Example: Divide By Zero Without Exception Handling 13.4 Example: Handling and 13.5 When to Use Exception Handling 13.6 Java Exception Hierarchy 13.7 block 13.8 Stack Unwinding 13.9, and 13.10 Chained Exceptions 13.11 Declaring New Exception Types 13.12 Preconditions and Postconditions 13.13 Assertions 13.14 Wrap-Up 4 13.1 Introduction Exception an indication of a problem that occurs during a program s execution Exception handling resolving exceptions that may occur so program can continue or terminate gracefully Exception handling enables programmers to create programs that are more robust and faulttolerant 5 Error-Prevention Tip 13.1 Exception handling helps improve a program s fault tolerance. 6 1

13.1 Introduction 7 13.2 Exception-Handling Overview 8 Examples an attempt is made to access an element past the end of an array an attempt is made to cast an object that does not have an is-a relationship with the type specified in the cast operator when a reference is used where an object is expected Intermixing program logic with error-handling logic can make programs difficult to read, modify, maintain and debug Exception handling enables programmers to remove error-handling code from the main line of the program s execution Improves clarity Enhances modifiability Performance Tip 13.1 If the potential problems occur infrequently, intermixing program and error-handling logic can degrade a program s performance, because the program must perform (potentially frequent) tests to determine whether the task executed correctly and the next task can be performed. 9 13.3 Example: Divide By Zero Without Exception Handling Thrown exception an exception that has occurred Stack trace Name of the exception in a descriptive message that indicates the problem Complete method-call stack can arise from a number of different problems in arithmetic Throw point initial point at which the exception occurs, top row of call chain occurs when method receives a string that does not represent a valid integer 10 1 ""$%&'%&()*+,%-* 2 *./% 3 -*%%0 -*%%0 4 5. )*+, )*+, 6 1 7 * *2..2/ / Attempt to divide; 8.. 34 34 5 5 6 6 may be zero 9 1 10 "0 "0"".*./ "".*./ 11 73 3 12 13.. * *4896 4896 14 1 15 : 4%60 4%60"" 16 17 %%4; ; (;60 60 18 :%460 :%460 Read input; exception occurs if 19 %%4; ; (; (;60 60 input is not a valid integer 20 :%460 :%460 21 22 :34560 :34560 23 %% 4 24 ;<=(>">:> =(>">:><; ;55560 55560 25 7"" "" 26 7)*+, )*+, 11 (&?? (@ =(&??"@:&A (&?? (? ;;-*%%("./ )*+,%34)*+,%-*(&?6 )*+,%4)*+,%-*(BB6 (&?? ( ( ;;-*%% -*%%%$4C6 -*%%%4C6 -*%%%4C6 -*%%%4C6 4C6 )*+,%4)*+,%-*(B?6 12 (&?? (@ =(&??"@:&A 2

13.4 Example: Handling ArithmeticExceptions and InputMismatchExceptions 13 Enclosing Code in a Block 14 With exception handling, the program catches and handles (i.e., deals with) the exception Next example allows user to try again if invalid input is entered (zero for denominator, or noninteger input) block encloses code that might throw an exception and the code that should not execute if an exception occurs Consists of keyword followed by a block of code enclosed in curly braces Software Engineering Observation 13.1 Exceptions may surface through explicitly mentioned code in a block, through calls to other methods, through deeply nested method calls initiated by code in a block or from the Java Virtual Machine as it executes Java bytecodes. 15 Catching Exceptions block catches (i.e., receives) and handles an exception, contains: Begins with keyword Exception parameter in parentheses exception parameter identifies the exception type and enables block to interact with caught exception object Block of code in curly braces that executes when exception of proper type occurs Matching block the type of the exception parameter matches the thrown exception type exactly or is a superclass of it Uncaught exception an exception that occurs for which there are no matching blocks Cause program to terminate if program has only one thread; Otherwise only current thread is terminated and there may be adverse effects to the rest of the program 16 17 18 Common Programming Error 13.1 Common Programming Error 13.2 It is a syntax error to place code between a block and its corresponding blocks. Each block can have only a single parameter specifying a comma-separated list of exception parameters is a syntax error. 3

19 20 Termination Model of Exception Handling When an exception occurs: block terminates immediately Program control transfers to first matching block After exception is handled: Termination model of exception handling program control does not return to the throw point because the block has expired; Flow of control proceeds to the first statement after the last block Resumption model of exception handling program control resumes just after throw point statement consists of block and corresponding and/or blocks Common Programming Error 13.3 Logic errors can occur if you assume that after an exception is handled, control will return to the first statement after the throw point. 21 22 Error-Prevention Tip 13.2 With exception handling, a program can continue executing (rather than terminating) after dealing with a problem. This helps ensure the kind of robust applications that contribute to what is called mission-critical computing or businesscritical computing. Good Programming Practice 13.1 Using an exception parameter name that reflects the parameter s type promotes clarity by reminding the programmer of the type of exception being handled. Using the Clause clause specifies the exceptions a method may throws Appears after method s parameter list and before the method s body Contains a comma-separated list of exceptions Exceptions can be thrown by statements in method s body of by methods called in method s body Exceptions can be of types listed in clause or subclasses 23 Error-Prevention Tip 13.3 If you know that a method might throw an exception, include appropriate exceptionhandling code in your program to make it more robust. 24 4

25 26 Error-Prevention Tip 13.4 Read the online API documentation for a method before using that method in a program. The documentation specifies the exceptions thrown by the method (if any) and indicates reasons why such exceptions may occur. Then provide for handling those exceptions in your program. Error-Prevention Tip 13.5 Read the online API documentation for an exception class before writing exceptionhandling code for that type of exception. The documentation for an exception class typically contains potential reasons that such exceptions occur during program execution. 1 ""$%&'%B()*+D,%-* 2 ""2 *2..2/% /% 3 -*%%0 -*%%0 4 -*%%0 -*%%0 5 6. )*+D, )*+D, 7 1 8 *2..2/ / 9.. 34 34 5 5 6 6 10 clause specifies that 11 1 method 3 may throw 12 "0 "0"".* "".*./ an./ 13 73 3 14 15.. * *4896 4896 16 1 17 : 4%60 4%60"" 18..E: E: Repetition statement 0 0"" loops until 19 block completes successfully 20 block attempts to read input 21 1 and perform division 22.3.3 23 1 24 %%4 %%4; ; (;60 60 25 :%460 :%460 26 %%4 %%4; ; (;60 60 Retrieve input; 27 :%460 :%460 28 thrown if input not valid integers 27 29 :34560 :34560 30 %% 4;<=(>">:> =(>">:><; ;55 55 31 560 560 Call method 3, which 32 E: 0 0"" 0 If we have reached this point, input may throw 33 7 7"" was valid and 34 46 46 35 1 was non-zero, so looping can stop 36 %% 4;<(> (><; ;5 Catching 37 60 60 (user has entered non-integer input) 38 %E460 %E460"" Exception parameters 39 %%4 %%4 40 ;F% %<; Read invalid ;60 input 60 but do nothing with it 41 7 7"" 42 46 46 43 1 44 %% 4;<(> (><; ;560 560 Catching Notify user of error made (user has 45 %%4 %%4 entered zero for denominator) 46 ;+*% %<; ;60 60 47 7 7"" 48 7 7 4E60 4E60""%%% ""%%% 49 7"" 50 7)*+D, )*+D, If line 32 was never successfully reached, loop continues and user can try again 28 (&?? (@ =(&??"@:&A 29 13.5 When to Use Exception Handling 30 (&?? (? (-*%%("./ +*% % % (&?? (@ =(&??"@:&A (&?? ( (-*%% F% % (&?? (@ Exception handling designed to process synchronous errors Synchronous errors occur when a statement executes Asynchronous errors occur in parallel with and independent of the program s flow of control =(&??"@:&A 5

31 32 Software Engineering Observation 13.2 Incorporate your exception-handling strategy into your system from the design process s inception. Including effective exception handling after a system has been implemented can be difficult. Software Engineering Observation 13.3 Exception handling provides a single, uniform technique for processing problems. This helps programmers working on large projects understand each other s error-processing code. 33 34 Software Engineering Observation 13.4 Software Engineering Observation 13.5 Avoid using exception handling as an alternate form of flow of control. These additional exceptions can get in the way of genuine errortype exceptions. Exception handling simplifies combining software components and enables them to work together effectively by enabling predefined components to communicate problems to application-specific components, which can then process the problems in an application-specific manner. 13.6 Java Exception Hierarchy 35 36 All exceptions inherit either directly or indirectly from class Exception classes form an inheritance hierarchy that can be extended Class., superclass of Only. objects can be used with the exceptionhandling mechanism Has two subclasses: and Class and its subclasses represent exception situations that can occur in a Java program and that can be caught by the application Class and its subclasses represent abnormal situations that could happen in the JVM it is usually not possible for a program to recover from s Fig. 13.3 Portion of class. s inheritance hierarchy. 6

13.6 Java Exception Hierarchy Two categories of exceptions: checked and unchecked Checked exceptions Exceptions that inherit from class but not from = Compiler enforces a catch-or-declare requirement Compiler checks each method call and method declaration to determine whether the method checked exceptions. If so, the compiler ensures that the checked exception is caught or is declared in a clause. If not caught or declared, compiler error occurs. Unchecked exceptions Inherit from class = or class Compiler does not check code to see if exception is caught or declared If an unchecked exception occurs and is not caught, the program terminates or runs with unexpected results Can typically be prevented by proper coding 37 Software Engineering Observation 13.6 Programmers are forced to deal with checked exceptions. This results in more robust code than would be created if programmers were able to simply ignore the exceptions. 38 39 40 Common Programming Error 13.4 A compilation error occurs if a method explicitly attempts to throw a checked exception (or calls another method that throws a checked exception) and that exception is not listed in that method s clause. Common Programming Error 13.5 If a subclass method overrides a superclass method, it is an error for the subclass method to list more exceptions in its clause than the overridden superclass method does. However, a subclass s clause can contain a subset of a superclass s list. 41 42 Software Engineering Observation 13.7 If your method calls other methods that explicitly throw checked exceptions, those exceptions must be caught or declared in your method. If an exception can be handled meaningfully in a method, the method should catch the exception rather than declare it. Software Engineering Observation 13.8 Although the compiler does not enforce the catchor-declare requirement for unchecked exceptions, provide appropriate exception-handling code when it is known that such exceptions might occur. For example, a program should process the.$ from method, even though.$ (a subclass of =) is an unchecked exception type. This makes your programs more robust. 7

13.6 Java Exception Hierarchy block catches all exceptions of its type and subclasses of its type If there are multiple blocks that match a particular exception type, only the first matching block executes It makes sense to use a block of a superclass when all the blocks for that class s subclasses will perform the same functionality 43 Error-Prevention Tip 13.6 Catching subclass types individually is subject to error if you forget to test for one or more of the subclass types explicitly; catching the superclass guarantees that objects of all subclasses will be caught. Positioning a block for the superclass type after all other subclass blocks for subclasses of that superclass ensures that all subclass exceptions are eventually caught. 44 Common Programming Error 13.6 Placing a block for a superclass exception type before other blocks that catch subclass exception types prevents those blocks from executing, so a compilation error occurs. 45 13.7 block Programs that obtain certain resources must return them explicitly to avoid resource leaks block Consists of keyword followed by a block of code enclosed in curly braces Optional in a statement If present, is placed after the last block Executes whether or not an exception is thrown in the corresponding block or any of its corresponding blocks Will not execute if the application exits early from a block via method % Typically contains resource-release code 46 Error-Prevention Tip 13.7 A subtle issue is that Java does not entirely eliminate memory leaks. Java will not garbage collect an object until there are no more references to it. Thus, memory leaks can occur, if programmers erroneously keep references to unwanted objects. 47 1 statements resource-acquisition statements 7"" 4 4AKindOfExceptionexception16 6 1 exception-handling statements 7"" % % % 4 4AnotherKindOfExceptionexception26 6 1 exception-handling statements 7"" 1 statements resource-release statements 7"" Fig. 13.4 Position of the finally block after the last catch block in a try statement. Outline 48 8

13.7 block If no exception occurs, blocks are skipped and control proceeds to block. After the block executes control proceeds to first statement after the block. If exception occurs in the block, program skips rest of the block. First matching the block executes and control proceeds to the block. If exception occurs and there are no matching blocks, control proceeds to the block. After the block executes, the program passes the exception to the next outer the block. If block throws an exception, the block still executes. 49 Performance Tip 13.2 Always release each resource explicitly and at the earliest possible moment at which it is no longer needed. This makes resources immediately available to be reused by your program or by other programs, thus improving resource utilization. 50 Error-Prevention Tip 13.8 Because the block is guaranteed to execute whether or not an exception occurs in the corresponding block, this block is an ideal place to release resources acquired in a block. This is also an effective way to eliminate resource leaks. For example, the block should close any files opened in the block. 51 13.7 block Standard streams % standard output stream % standard error stream % can be used to separate error output from regular output %% and %% display data to the command prompt by default 52 1 ""$%&'%G(C%-* 2 "") %%%%%% 3 ""% 4 5. C C 6 1 7.. * *4896 4896 8 1 9 10 1 11 460 12 7"" 13 46 46.. Call method that throws an exception 14 1 15 %%4;; ;;60 60 16 7"" 17 18 460 19 7"" 20 53 21 ""%%%%%% 22.. * *46 46 23 1 24 25 1 26 %%4;; ;;60 60 27 460 460"" 28 7"" 29 46 46 Create new and throw it 30 1 31 %%4 32 ; ;; ;60 60 33 0 0"" 34 35.. Throw previously created 36 37 7"" 38 %%% 39 1 40 %%4 %%4;$; ;$;60 block executes even though 60 41 7 7"" exception is rethrown in block 42 54 43..5 5 44 9

45 7 46 47 "" 48.. * *46 46 49 1 50 "". "". 51 1 52 %%4 4;; ;;60 60 53 7"" 54 46 46 55 1 56 %%460 57 7"" 58 %%% 59 1 60 %%4 %%4 block executes even though no 61 ;$; ;$;60 60 exception is thrown 62 7 7"" 63 55 Throwing Exceptions Using the Statement statement used to throw exceptions Programmers can thrown exceptions themselves from a method if something has gone wrong statement consists of keyword followed by the exception object 56 64 %%4; ;60 60 65 7 66 7C C $ $ 57 58 Software Engineering Observation 13.9 Software Engineering Observation 13.10 When is invoked on any. object, its resulting string includes the descriptive string that was supplied to the constructor, or simply the class name if no string was supplied. An object can be thrown without containing information about the problem that occurred. In this case, simple knowledge that an exception of a particular type occurred may provide sufficient information for the handler to process the problem correctly. Software Engineering Observation 13.11 Exceptions can be thrown from constructors. When an error is detected in a constructor, an exception should be thrown rather than creating an improperly formed object. 59 Rethrowing Exceptions Exceptions are rethrown when a block decides either that it cannot process the exception or that it can only partially process it Exception is deferred to outer statement Exception is rethrown by using keyword followed by a reference to the exception object 60 10

61 62 Common Programming Error 13.7 If an exception has not been caught when control enters a block and the block throws an exception that is not caught in the block, the first exception will be lost and the exception from the block will be returned to the calling method. Error-Prevention Tip 13.9 Avoid placing code that can an exception in a block. If such code is required, enclose the code in a statement within the block. 63 64 Common Programming Error 13.8 Assuming that an exception thrown from a block will be processed by that block or any other block associated with the same statement can lead to logic errors. Good Programming Practice 13.2 Java s exception-handling mechanism is intended to remove error-processing code from the main line of a program s code to improve program clarity. Do not place %%% %%% around every statement that may throw an exception. This makes programs difficult to read. Rather, place one block around a significant portion of your code, follow that block with blocks that handle each possible exception and follow the blocks with a single block (if one is required). 13.8 Stack Unwinding 65 1 ""$%&'%H(C%-* 2 "") % 3 4. C C 5 1 66 Stack unwinding When an exception is thrown but not caught in a particular scope, the methodcall stack is unwound, and an attempt is made to catch the exception in the next outer block. When unwinding occurs: The method in which the exception was not caught terminates All local variables in that method go out of scope Control returns to the statement that originally invoked the method if a try block encloses the method call, an attempt is made to catch the exception. 6.. * *4896 4896 7 1 8 Call method that throws an exception 9 1 1 10 460 460 11 7"" 12 46 46 13 1 14 %%4;; ;;60 Catch exception 60 that may occur in the 15 7"" above block, including the call to 16 7"" " method 17 11

18 19.. * *46 46 20 1 21 Method throws exception 22 1 23 %%4; ;; ;60 60 24 460 460"" 25 7"" 26 4=6 4=6 Throw new exception; Exception not 27 1 caught in current block, so 28 %%4 handled in outer block 29 ; ;; ;60 60 30 7"" 31 "". block executes before 32 1 control returns to outer block 33 %%4;$; ;$;60 60 34 7"" 35 7 36 7C C $ 67 13.9, and Methods in class. retrieve more information about an exception outputs stack trace to standard error stream retrieves stack trace information as an array of objects; enables custom processing of the exception information returns the descriptive string stored in an exception 68 69 70 Error-Prevention Tip 13.10 An exception that is not caught in an application causes Java s default exception handler to run. This displays the name of the exception, a descriptive message that indicates the problem that occurred and a complete execution stack trace. In an application with a single thread of execution, the application terminates. In an application with multiple threads, the thread that caused the exception terminates. Error-Prevention Tip 13.11. method (inherited by all. subclasses) returns a string containing the name of the exception s class and a descriptive message. 13.9, and methods $ E. Stack trace information follows pattern classname.methodname(filename:linenumber) 71 1 ""$%&'%@(C%-* 2 "") % 3 4. C C 5 1 6.. * *4896 4896 Call to &, & calls 7 1 B, B calls ' and 8 ' throws a new 9 1 10 &460 &460""& ""& Display descriptive string of 11 7"" exception thrown in ' 12 46 46& & 13 1 14 %% 4;> ;><<; ;5 5%46 %4660 60 Retrieve stack information as an array 15 %460 %460 " 16 of objects 17 "". "".2 18 89:%460 89:%460 19 Display stack trace for exception thrown in ' 72 12

20 %%4;< (;60 60 21 %%4; ;<<$ $<<<E E<; ;60 60 Retrieve class name for current 22 23 24 4 4(6 (6 Retrieve file name for current 25 1 26 %% 4;> 4 ;><; ;5 5%46 %4660 60 Retrieve line number for current 27 %% 4;> ;><; ;5 5%$46 %$4660 60 28 %% 4;> ;><; ;5 5%E.46 %E.4660 60 29 %% 4;> ;><; ;5 5%46 %4660 60 Retrieve method name for current 30 7"" 31 7"" 32 7"" & calls B, B calls 33 ' and ' throws an 34 ""B0. 35.. * *&46 &46 36 1 37 B460 B460 38 7& & 39 73 40 ""'0.& 41.. * *B46 B46 42 1 43 '460 '460 44 7B B 45 46.B 47.. * * '46 '46 48 1 49 4 4;'; ;';60 60 50 7' ' 51 7C C ' -*%%(' C%'4C%-*(AI6 C%'4C%-*(AI6 C%B4C%-*(A'6 C%&4C%-*('@6 C%4C%-*(&?6 ( ( $E CC%-*AI' CC%-*A'B CC%-*'@& CC%-*&? %-*&? B calls ', which throws an Exception created and thrown 74 Software Engineering Observation 13.12 Never ignore an exception you catch. At least use to output an error message. This will inform users that a problem exists, so that they can take appropriate actions. 75 13.10 Chained Exceptions Chained exceptions enable an exception object to maintain the complete stack-trace information when an exception is thrown from a catch block Users can retrieve information about original exception Stack trace from a chained exception displays how many chained exceptions remain 76 1 ""$%&'%J(C%-* 2 "")% 3 4. C C 5 1 6.. * *4896 4896 7 1 8 9 1 10 &460 &460"" ""& & 11 7"" 12 46 46 & 13 1 14 %460 15 7"" 16 7"" 17 Catch exception from & as well as any associated chained exceptions 77 18 ""B0. ""B0. 19.. * *&46 &46 D D 20 1 21 22 1 23 B460 B460""B ""B 24 7"" 25 46 46 " B 26 1 27 4 4;&; ;&;560 560 28 7"" 29 7& & 30 31 ""'0.& ""'0.& 32.. * *B46 B46 33 1 34 35 1 36 '460 '460""' ""' 37 7"" 38 46 46 ' 39 1 40 4 4;B; ;B;560 560 41 7"" 42 7B B 43 Catch exception from B, throw new exception to be chained with earlier exceptions Catch exception from ', throw new exception to be chained with earlier exceptions 78 13

44.B.B 45.. * *'46 '46 46 1 47 4 4;'; ;';60 60 48 7' ' 49 7C C Original thrown exception -*%%(& %(& C%&4C%-*(B@6 C%4C%-*(&?6.(-*%%(B C%B4C%-*(A?6 C%B4C%-*(A?6 C%&4C%-*(B'6 %%%&.(-*%%(' C%'4C%-*(A@6 '4C%-*(A@6 C%B4C%-*('H6 %%%B 79 13.11 Declaring New Exception Types You can declare your own exception classes that are specific to the problems that can occur when another program uses your reusable classes New exception class must extend an existing exception class Typically contains only two constructors One takes no arguments, passes a default exception messages to the superclass constructor One that receives a customized exception message as a string and passes it to the superclass constructor 80 81 82 Software Engineering Observation 13.13 Good Programming Practice 13.3 If possible, indicate exceptions from your methods by using existing exception classes, rather than creating new exception classes. The Java API contains many exception classes that might be suitable for the type of problem your method needs to indicate. Associating each type of serious execution-time malfunction with an appropriately named class improves program clarity. 83 84 Software Engineering Observation 13.14 When defining your own exception type, study the existing exception classes in the Java API and try to extend a related exception class. For example, if you are creating a new class to represent when a method attempts a division by zero, you might extend class because division by zero occurs during arithmetic. If the existing classes are not appropriate superclasses for your new exception class, decide whether your new class should be a checked or an unchecked exception class. (cont ) Software Engineering Observation 13.14 The new exception class should be a checked exception (i.e., extend but not =) if possible clients should be required to handle the exception. The client application should be able to reasonably recover from such an exception. The new exception class should extend = if the client code should be able to ignore the exception (i.e., the exception is an unchecked exception). 14

85 86 Good Programming Practice 13.4 By convention, all exception-class names should end with the word. 13.12 Preconditions and Postconditions Preconditions and postconditions are the states before and after a method s execution Used to facilitate debugging and improve design You should state the preconditions and postconditions in a comment before the method declaration 13.12 Preconditions and Postconditions 87 13.13 Assertions 88 Preconditions Condition that must be true when the method is invoked Describe method parameters and any other expectations the method has about the current state of a program If preconditions not met, method s behavior is undefined Postconditions Condition that is true after the method successfully returns Describe the return value and any other side-effects the method may have When calling a method, you may assume that a method fulfills all of its postconditions Assertions are conditions that should be true at a particular point in a method Help ensure a program s validity by catching potential bugs Preconditions and Postconditions are two kinds of assertions Assertions can be stated as comments or assertions can be validated programmatically using the statement 13.13 Assertions statement Evaluates a. expression and determines whether it is or Two forms expression0 -- is thrown if expression is expression1 (expression20 -- is thrown if expression1 is, expression2 is error message Used to verify intermediate states to ensure code is working correctly Used to implement preconditions and postconditions programmatically By default, assertions are disabled Assertions can be enabled with the K command-line option 89 1 ""$%&'%I(%-* 2 "") 3 -*%%0 -*%%0 4 5. 6 1 7.. * *4896 4896 8 1 9 : 4%60 4%60 10 11 %%4;..?&?(; ;..?&?(;60 60 12.:%460.:%460 statement 13 14.*L:?.*L:? 15 4.L:?MM.N:&?6( 4.L:?MM.N:&?6(;..(; ;..(;O. O.0 0 16 17 %% 4;F> ;F><; ;5.60 5.60 If. is less than 0 or greater 18 7"" 19 7 than 10, occurs..?&?(g FG..?&?(G? ;;-*%%(..(G? %(..(G? %4%-*(&G6 Message to be displayed with 90 15