C++ Exception Handling

Slides:



Advertisements
Similar presentations
Pearson Education, Inc. All rights reserved. 1.. Exception Handling.
Advertisements

 2003 Prentice Hall, Inc. All rights reserved. 1 Chapter 13 - Exception Handling Outline 13.1 Introduction 13.2 Exception-Handling Overview 13.3 Other.
Exception Handling The purpose of exception handling is to permit the program to catch and handle errors rather than letting the error occur and suffer.
Exception Handling Chapter 15 2 What You Will Learn Use try, throw, catch to watch for indicate exceptions handle How to process exceptions and failures.
An Introduction to Java Programming and Object- Oriented Application Development Chapter 8 Exceptions and Assertions.
C++ Programming: Program Design Including Data Structures, Fourth Edition Chapter 15: Exception Handling.
Review Linked list: Doubly linked list, insertback, insertbefore Remove Search.
Copyright © 2008 Pearson Addison-Wesley. All rights reserved. Chapter 16 Exception Handling.
 2006 Pearson Education, Inc. All rights reserved. Exception Handling in C++ CS-2303, C-Term Exception Handling in C++ CS-2303 System Programming.
Exception Handling and Format output
 2000 Prentice Hall, Inc. All rights reserved. Chapter 23 - Exception Handling Outline 23.1Introduction 23.2When Exception Handling Should Be Used 23.3Other.
Chapter 16: Exception Handling C++ Programming: From Problem Analysis to Program Design, Fifth Edition.
Objectives In this chapter you will: Learn what an exception is Learn how to handle exceptions within a program See how a try / catch block is used to.
 Both System.out and System.err are streams—a sequence of bytes.  System.out (the standard output stream) displays output  System.err (the standard.
Exception Handling Yaodong Bi Exception Handling Java exception handling Try blocks Throwing and re-throwing an exception Catching an.
Exception Handling 1 CISC6795, Spring Introduction 2 Exception – an indication of a problem that occurs during a program’s execution, for examples:
 2005 Pearson Education, Inc. All rights reserved Exception Handling.
Nirmalya Roy School of Electrical Engineering and Computer Science Washington State University Cpt S 122 – Data Structures Exception Handling: A Deeper.
C++ Programming: From Problem Analysis to Program Design, Third Edition Chapter 16: Exception Handling.
Lesson 16 Exceptions Lesson Exceptions1. Murphy’s Law Anything that can go wrong will go wrong Lesson Exceptions2.
Jerry Lebowitz. Topics  Provides a facility for a systematic object oriented approach to handling runtime errors ◦ Can also handle runtime errors.
1 CSC241: Object Oriented Programming Lecture No 28.
Exception Handling 1 -Based on slides from Deitel & Associates, Inc. - Revised by T. A. Yang.
Microsoft VB 2005: Reloaded, Advanced Chapter 5 Input Validation, Error Handling, and Exception Handling.
Exception Handling An Exception is an indication of a problem that occurs during a program’s execution. Exception handling enables the programmer to create.
© Copyright Eliyahu Brutman Programming Techniques Course Version 1.0.
 2006 Pearson Education, Inc. All rights reserved Exception Handling.
 2006 Pearson Education, Inc. All rights reserved Exception Handling.
 2006 Pearson Education, Inc. All rights reserved Exception Handling.
C How to Program, 6/e © by Pearson Education, Inc. All Rights Reserved.
Dale Roberts Exception Handling Dale Roberts, Lecturer Computer Science, IUPUI Department of Computer and Information Science,
Slides prepared by Rose Williams, Binghamton University ICS201 Lecture 9 : Exception Handling King Fahd University of Petroleum & Minerals College of Computer.
Object Oriented Programming
 2000 Deitel & Associates, Inc. All rights reserved. Chapter 13 - Exception Handling Outline 13.1Introduction 13.2When Exception Handling Should Be Used.
Chapter 12: Exception Handling
Pemrograman VisualMinggu …12… Page 1 MINGGU Ke Duabelas Pemrograman Visual Pokok Bahasan: Exception Handling Tujuan Instruksional Khusus: Mahasiswa dapat.
Slides Credit Umair Javed LUMS Web Application Development.
Exception Handling. 2 Two types of bugs (errors) Logical error Syntactic error Logical error occur  Due to poor understanding of the problem and solution.
CMSC 202 Exceptions. Aug 7, Error Handling In the ideal world, all errors would occur when your code is compiled. That won’t happen. Errors which.
Introduction to Exception Handling and Defensive Programming.
Chapter 14: Exception Handling. Objectives In this chapter, you will: – Learn what an exception is – Learn how to handle exceptions within a program –
Android How to Program, 2/e © Copyright by Pearson Education, Inc. All Rights Reserved.
Exceptions in Java. Exceptions An exception is an object describing an unusual or erroneous situation Exceptions are thrown by a program, and may be caught.
Exception Handling Programmers must deal with errors and exceptional situations: User input errors Device errors Empty disk space, no memory Component.
HANDLING EXCEPTIONS Chapter 9. Outline  Learn about the limitations of traditional error-handling methods  Throw exceptions  Use try blocks  Catch.
Unit 4 School of Information Systems & Technology1 School of Information Systems and Technology (IST)
CSE 332: C++ Statements C++ Statements In C++ statements are basic units of execution –Each ends with ; (can use expressions to compute values) –Statements.
Chapter 15: Exception Handling C++ Programming: Program Design Including Data Structures, Fifth Edition.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Chapter 23 - Exception Handling Outline 23.1Introduction.
Exception Handling in C++. Outline What exceptions are and when to use them Using try, catch and throw to detect, handle and indicate exceptions, respectively.
Exception Handling Outline 23.1 Introduction
CS212: Object Oriented Analysis and Design Lecture 19: Exception Handling.
CSCI 383 Object-Oriented Programming & Design Lecture 20 Martin van Bommel.
1 Exceptions. 2 Syntax Errors, Runtime Errors, and Logic Errors syntax errors, runtime errors, and logic errors You learned that there are three categories.
CMSC 202 Computer Science II for Majors. CMSC 202UMBC Topics Exceptions Exception handling.
EE4E. C++ Programming Lecture 6 Advanced Topics. Contents Introduction Introduction Exception handling in C++ Exception handling in C++  An object oriented.
ECE122 L23: Exceptions December 6, 2007 ECE 122 Engineering Problem Solving with Java Lecture 24 Exceptions.
Lecture 18B Exception Handling and Richard Gesick.
CSE 332: C++ Exceptions Motivation for C++ Exceptions Void Number:: operator/= (const double denom) { if (denom == 0.0) { // what to do here? } m_value.
Appendix H Exception Handling: A Deeper Look
C ++ MULTIPLE CHOICE QUESTION
Exception Handling in C++
IS 0020 Program Design and Software Tools
16 Exception Handling.
Chapter 16 Exception Handling: A Deeper Look
Why exception handling in C++?
Chapter 14: Exception Handling
16 Exception Handling.
CMSC 202 Exceptions.
Exception Handling.
Presentation transcript:

C++ Exception Handling

Outline What exceptions are and when to use them Using try, catch and throw to detect, handle and indicate exceptions, respectively To understand the standard exception hierarchy Exception Handling in C++

Introduction Exceptions Exception handling Indicate problems that occur during a program’s execution Occur infrequently Exception handling Can resolve exceptions Allow a program to continue executing or Notify the user of the problem and Terminate the program in a controlled manner Makes programs robust and fault-tolerant Exception Handling in C++

Exception Handling in C++ A standard mechanism for processing errors Especially important when working on a project with a large team of programmers C++ exception handling is much like Java’s Java’s exception handling is much like C++ Exception Handling in C++

Fundamental Philosophy Mechanism for sending an exception signal up the call stack Regardless of intervening calls Note: there is a mechanism based on same philosophy in C setjmp(), longjmp() See man pages Exception Handling in C++

Traditional Exception Handling Intermixing program and error-handling logic Pseudocode outline Perform a task If the preceding task did not execute correctly Perform error processing Perform next task If the preceding task did not execute correctly Perform error processing … Makes the program difficult to read, modify, maintain and debug Impacts performance Note:– In most large systems, code to handle errors and exceptions represents >80% of the total code of the system Exception Handling in C++

Fundamental Philosophy (continued) Remove error-handling code from the program execution’s “main line” Programmers can handle any exceptions they choose All exceptions All exceptions of a certain type All exceptions of a group of related types Exception Handling in C++

Fundamental Philosophy (continued) Programs can Recover from exceptions Hide exceptions Pass exceptions up the “chain of command” Ignore certain exceptions and let someone else handle them Exception Handling in C++

Fundamental Philosophy (continued) An exception is a class Usually derived from one of the system’s exception base classes If an exceptional or error situation occurs, program throws an object of that class Object crawls up the call stack A calling program can choose to catch exceptions of certain classes Take action based on the exception object Exception Handling in C++

Class exception The standard C++ base class for all exceptions Provides derived classes with virtual function what Returns the exception’s stored error message Exception Handling in C++

Example: Handling an Attempt to Divide by Zero Exception Handling in C++

Zero Divide Example Fig27-2 (1 of 2) Exception Handling in C++

Zero Divide Example Fig27-2 (2 of 2) Exception Handling in C++

Questions? Exception Handling in C++

Keyword try followed by braces ({}) Should enclose try Blocks Keyword try followed by braces ({}) Should enclose Statements that might cause exceptions Statements that should be skipped in case of an exception Exception Handling in C++

Software Engineering Observation Exceptions may surface through explicitly mentioned code in a try block, through calls to other functions and through deeply nested function calls initiated by code in a try block. Exception Handling in C++

“If they’re running and they don’t look where they’re going I have to come out from somewhere and catch them.” - J. D. Salinger, Catcher in the Rye

Catch Handlers Immediately follow a try block Keyword catch One or more catch handlers for each try block Keyword catch Exception parameter enclosed in parentheses Represents the type of exception to process Can provide an optional parameter name to interact with the caught exception object Executes if exception parameter type matches the exception thrown in the try block Could be a base class of the thrown exception’s class Exception Handling in C++

Catch Handlers (continued) try { // code to try } catch (exceptionClass1 &name1) { // handle exceptions of exceptionClass1 catch (exceptionClass2 &name2) { // handle exceptions of exceptionClass2 catch (exceptionClass3 &name3) { // handle exceptions of exceptionClass3 ... /* code to execute if no exception or catch handler handled exception*/ All other classes of exceptions are not handled here catch clauses attempted in order; first match wins! Exception Handling in C++

Common Programming Errors Syntax error to place code between a try block and its corresponding catch handlers Each catch handler can have only a single parameter Specifying a comma-separated list of exception parameters is a syntax error Logic error to catch the same type in two different catch handlers following a single try block Exception Handling in C++

Fundamental Philosophy (continued) Termination model of exception handling try block expires when an exception occurs Local variables in try block go out of scope Code within the matching catch handler executes Control resumes with the first statement after the last catch handler following the try block Stack unwinding Occurs if no matching catch handler is found Program attempts to locate another enclosing try block in the calling function Control does not return to throw point Exception Handling in C++

Think about… Handling exceptions in your Zoo program What exceptions could happen? What will you do to handle them?

Stack Unwinding Occurs when a thrown exception is not caught in a particular scope Unwinding a Function terminates that function All local variables of the function are destroyed Invokes destructors Control returns to point where function was invoked Attempts are made to catch the exception in outer try…catch blocks If the exception is never caught, the function terminate is called Exception Handling in C++

Observations With exception handling, a program can continue executing (rather than terminating) after dealing with a problem. This helps to support robust applications that contribute to mission-critical computing or business-critical computing When no exceptions occur, there is no performance penalty Exception Handling in C++

Throwing an Exception Use keyword throw followed by an operand representing the type of exception The throw operand can be of any type If the throw operand is an object, it is called an exception object The throw operand initializes the exception parameter in the matching catch handler, if one is found Exception Handling in C++

Notes Catching an exception object by reference eliminates the overhead of copying the object that represents the thrown exception Associating each type of runtime error with an appropriately named exception object improves program clarity. Exception Handling in C++

When to Use Exception Handling Don’t use for routine stuff such as end-of-file or null string checking To process synchronous errors Occur when a statement executes Not to process asynchronous errors Occur in parallel with, and independent of, program execution To process problems arising in predefined software elements Such as predefined functions and classes Error handling can be performed by the program code to be customized based on the application’s needs Exception Handling in C++

Software Engineering Notes Incorporate exception-handling strategy into system design from the start Very difficult to retrofit after the system has been implemented! Exception handling provides uniform technique for processing problems Helps with understandability of each other’s error handling code Avoid using exception handling as an alternate form of flow of control These “additional” exceptions can “get in the way” of genuine error handling Exception Handling in C++ CS-2303, C-Term 2010

Rethrowing an Exception Empty throw; statement Use when a catch handler cannot or can only partially process an exception Next enclosing try block attempts to match the exception with one of its catch handlers Exception Handling in C++ CS-2303, C-Term 2010

Common Programming Error Executing an empty throw statement outside a catch handler causes a function call to terminate Abandons exception processing and terminates the program immediately Exception Handling in C++ CS-2303, C-Term 2010

Exception Specifications Also called throw lists Keyword throw Comma-separated list of exception classes in parentheses Example int someFunction( double value ) throw ( ExceptionA, ExceptionB, ExceptionC ) { ... } Indicates someFunction can throw types ExceptionA, ExceptionB and ExceptionC Optional! Exception Handling in C++ CS-2303, C-Term 2010

Exception Specifications (continued) A function can throw only exceptions of types in its specification (or derived types) If a function throws a non-specification exception, function unexpected is called This normally terminates the program Absence of exception specification indicates that the function can throw any exception An empty exception specification, throw(), indicates the function cannot throw any exceptions Exception Handling in C++ CS-2303, C-Term 2010

Error Note The compiler will not generate a compilation error if a function contains a throw expression for an exception not listed in the function’s exception specification. Error occurs only when that function attempts to throw that exception at run time. To avoid surprises at execution time, carefully check your code to ensure that functions do not throw exceptions not listed in their exception specifications Exception Handling in C++ CS-2303, C-Term 2010

Questions? Exception Handling in C++ CS-2303, C-Term 2010

Constructors and Destructors Exceptions and constructors Exceptions enable constructors to report errors Unable to return values Exceptions thrown by constructors cause any already-constructed component objects to call their destructors Only those objects that have already been constructed will be destructed Exceptions and destructors Destructors are called for all automatic objects in the terminated try block when an exception is thrown Acquired resources can be placed in local objects to automatically release the resources when an exception occurs If a destructor invoked by stack unwinding throws an exception, function terminate is called Exception Handling in C++ CS-2303, C-Term 2010

Note When an exception is thrown from the constructor for an object that is created in a new expression, … … the dynamically allocated memory for that object is released. Exception Handling in C++ CS-2303, C-Term 2010

Exceptions and Inheritance New exception classes can be defined to inherit from existing exception classes A catch handler for a particular exception class can also catch exceptions of classes derived from that class Enables catching related errors with a concise notation Exception Handling in C++ CS-2303, C-Term 2010

Failure of calls to new Some compilers throw a bad_alloc exception Compliant to the C++ standard specification Some compilers return 0 C++ standard-compliant compilers also have a version of new that returns 0 Use expression new( nothrow ), where nothrow is of type nothrow_t Some compilers throw bad_alloc if <new> is included Exception Handling in C++ CS-2303, C-Term 2010

Standard Library Exception Hierarchy Base-class exception Contains virtual function what for storing error messages Exception classes derived from exception bad_alloc – thrown by new bad_cast – thrown by dynamic_cast bad_typeid – thrown by typeid bad_exception – thrown by unexpected Instead of terminating the program or calling the function specified by set_unexpected Used only if bad_exception is in the function’s throw list Exception Handling in C++ CS-2303, C-Term 2010

Fig. 27.11 | Standard Library exception classes. Exception Handling in C++ CS-2303, C-Term 2010

Exception Handling Summary Exceptions are derived from class exception Exceptional or error condition is indicated by throwing an object of that class Created by constructor in throw statement Calling programs can check for exceptions with try...catch construct Unified method of handling exceptions Far superior to coding exception handling in long hand No performance impact when no exceptions Exception Handling in C++ CS-2303, C-Term 2010

Exception Handling Summary (continued) Many more details — see Deitel & Deitel Any other textbook C++ standard Exception Handling in C++ CS-2303, C-Term 2010

Questions? Exception Handling in C++ CS-2303, C-Term 2010