SlideShare a Scribd company logo
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 To process uncaught and unexpected exceptions To declare new exception classes How stack unwinding enables exceptions not caught in one scope to be caught in another scope To handle new failures To understand the standard exception hierarchy Exception Handling in C++
Introduction Exceptions 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 Exception Handling in C++ Note:– In most large systems, code to  handle errors and exceptions represents >80% of the total code of the system
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++
Exception Handling in C++ Zero Divide Example Fig27-2 (1 of 2)
Exception Handling in C++ Zero Divide Example Fig27-2 (2 of 2)
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++
Catch   Handlers Immediately follow a  try  block 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*/ Exception Handling in C++ All other classes of exceptions are not handled here catch  clauses attempted in order; first match wins!
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 Exception Handling in C++ Control  does not  return to throw point
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 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++ Don’t use for routine stuff such as end-of-file or null string checking
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++
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++
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++ See D&D Fig 27.3
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 Exception Handling in C++ Optional!
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++
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++
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++
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++
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++
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++
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++
Fig. 27.11  | Standard Library exception classes.  Exception Handling in C++
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++
Exception Handling Summary  (continued) Many more details — see Deitel & Deitel Any other textbook C++ standard Exception Handling in C++

More Related Content

PPS
Exception handling in c programming
PPT
Exception handling in c++ by manoj vasava
PPTX
Exception handling chapter15
PPT
Exception handler
PPTX
Exception handling
PDF
Exception handling
PPTX
Exception Handling in C++
PPT
Exception handling and templates
Exception handling in c programming
Exception handling in c++ by manoj vasava
Exception handling chapter15
Exception handler
Exception handling
Exception handling
Exception Handling in C++
Exception handling and templates

What's hot (20)

PDF
Exception Handling
PPTX
What is Exception Handling?
PDF
14 exception handling
PPTX
Exception handling in c++
PPSX
Exception Handling
PDF
Exception handling
PPT
Exceptions in c++
PPTX
C++ ala
PDF
Exception Handling in the C++ Constructor
PPT
Handling Exceptions In C &amp; C++[Part A]
PPTX
Exception Handling in object oriented programming using C++
PPTX
Exception handling c++
PPT
Understanding Exception Handling in .Net
PPTX
7.error management and exception handling
PPTX
Presentation1
PPT
C# Exceptions Handling
PDF
Best Practices in Exception Handling
PDF
EXCEPTION HANDLING in C++
PPT
Exception Handling Java
ODP
Exception Handling In Java
Exception Handling
What is Exception Handling?
14 exception handling
Exception handling in c++
Exception Handling
Exception handling
Exceptions in c++
C++ ala
Exception Handling in the C++ Constructor
Handling Exceptions In C &amp; C++[Part A]
Exception Handling in object oriented programming using C++
Exception handling c++
Understanding Exception Handling in .Net
7.error management and exception handling
Presentation1
C# Exceptions Handling
Best Practices in Exception Handling
EXCEPTION HANDLING in C++
Exception Handling Java
Exception Handling In Java
Ad

Similar to Week7 exception handling (20)

PPTX
Lecture 1 Try Throw Catch.pptx
PPT
Exception and Error Handling in C++ - A detailed Presentation
PPTX
Lecture 3.1.1 Try Throw Catch.pptx
PPT
Week7_ExceptionHandling.ppt
PPT
Exception handling
PPT
Vc++ 4(exception handling)
PPTX
Lecture 09 Exception Handling(1 ) in c++.pptx
PPT
UNIT III.ppt
PPT
UNIT III (2).ppt
PDF
PDF
PPTX
Exception Handling in C++-Brief notes.pptx
PPT
Unit iii
PPT
Handling
PPTX
6-Exception Handling and Templates.pptx
PPTX
Object Oriented Programming Using C++: C++ Exception Handling.pptx
PPT
F6dc1 session6 c++
PPTX
WINSEM2016-17_CSE1002_LO_1336_24-JAN-2017_RM003_session 10.pptx
PPTX
Exceptions in C++ Object Oriented Programming.pptx
PPS
Aae oop xp_13
Lecture 1 Try Throw Catch.pptx
Exception and Error Handling in C++ - A detailed Presentation
Lecture 3.1.1 Try Throw Catch.pptx
Week7_ExceptionHandling.ppt
Exception handling
Vc++ 4(exception handling)
Lecture 09 Exception Handling(1 ) in c++.pptx
UNIT III.ppt
UNIT III (2).ppt
Exception Handling in C++-Brief notes.pptx
Unit iii
Handling
6-Exception Handling and Templates.pptx
Object Oriented Programming Using C++: C++ Exception Handling.pptx
F6dc1 session6 c++
WINSEM2016-17_CSE1002_LO_1336_24-JAN-2017_RM003_session 10.pptx
Exceptions in C++ Object Oriented Programming.pptx
Aae oop xp_13
Ad

Recently uploaded (20)

PPTX
Final Presentation General Medicine 03-08-2024.pptx
PPTX
Microbial diseases, their pathogenesis and prophylaxis
PDF
O7-L3 Supply Chain Operations - ICLT Program
PDF
STATICS OF THE RIGID BODIES Hibbelers.pdf
PDF
3rd Neelam Sanjeevareddy Memorial Lecture.pdf
PPTX
master seminar digital applications in india
PPTX
Institutional Correction lecture only . . .
PDF
BÀI TẬP BỔ TRỢ 4 KỸ NĂNG TIẾNG ANH 9 GLOBAL SUCCESS - CẢ NĂM - BÁM SÁT FORM Đ...
PDF
Basic Mud Logging Guide for educational purpose
PDF
Supply Chain Operations Speaking Notes -ICLT Program
PDF
Classroom Observation Tools for Teachers
PDF
grade 11-chemistry_fetena_net_5883.pdf teacher guide for all student
PDF
Module 4: Burden of Disease Tutorial Slides S2 2025
PDF
Chapter 2 Heredity, Prenatal Development, and Birth.pdf
PDF
Physiotherapy_for_Respiratory_and_Cardiac_Problems WEBBER.pdf
PPTX
human mycosis Human fungal infections are called human mycosis..pptx
PPTX
Pharmacology of Heart Failure /Pharmacotherapy of CHF
PDF
01-Introduction-to-Information-Management.pdf
PPTX
Cell Types and Its function , kingdom of life
PPTX
Lesson notes of climatology university.
Final Presentation General Medicine 03-08-2024.pptx
Microbial diseases, their pathogenesis and prophylaxis
O7-L3 Supply Chain Operations - ICLT Program
STATICS OF THE RIGID BODIES Hibbelers.pdf
3rd Neelam Sanjeevareddy Memorial Lecture.pdf
master seminar digital applications in india
Institutional Correction lecture only . . .
BÀI TẬP BỔ TRỢ 4 KỸ NĂNG TIẾNG ANH 9 GLOBAL SUCCESS - CẢ NĂM - BÁM SÁT FORM Đ...
Basic Mud Logging Guide for educational purpose
Supply Chain Operations Speaking Notes -ICLT Program
Classroom Observation Tools for Teachers
grade 11-chemistry_fetena_net_5883.pdf teacher guide for all student
Module 4: Burden of Disease Tutorial Slides S2 2025
Chapter 2 Heredity, Prenatal Development, and Birth.pdf
Physiotherapy_for_Respiratory_and_Cardiac_Problems WEBBER.pdf
human mycosis Human fungal infections are called human mycosis..pptx
Pharmacology of Heart Failure /Pharmacotherapy of CHF
01-Introduction-to-Information-Management.pdf
Cell Types and Its function , kingdom of life
Lesson notes of climatology university.

Week7 exception handling

  • 2. Outline What exceptions are and when to use them Using try , catch and throw to detect, handle and indicate exceptions, respectively To process uncaught and unexpected exceptions To declare new exception classes How stack unwinding enables exceptions not caught in one scope to be caught in another scope To handle new failures To understand the standard exception hierarchy Exception Handling in C++
  • 3. Introduction Exceptions 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++
  • 4. 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++
  • 5. 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++
  • 6. 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 Exception Handling in C++ Note:– In most large systems, code to handle errors and exceptions represents >80% of the total code of the system
  • 7. 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++
  • 8. 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++
  • 9. 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++
  • 10. 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++
  • 11. Example: Handling an Attempt to Divide by Zero Exception Handling in C++
  • 12. Exception Handling in C++ Zero Divide Example Fig27-2 (1 of 2)
  • 13. Exception Handling in C++ Zero Divide Example Fig27-2 (2 of 2)
  • 14. 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++
  • 15. 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++
  • 16. Catch Handlers Immediately follow a try block 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++
  • 17. 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*/ Exception Handling in C++ All other classes of exceptions are not handled here catch clauses attempted in order; first match wins!
  • 18. 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++
  • 19. 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 Exception Handling in C++ Control does not return to throw point
  • 20. 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++
  • 21. 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++
  • 22. 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++
  • 23. 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++
  • 24. When to Use Exception Handling 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++ Don’t use for routine stuff such as end-of-file or null string checking
  • 25. 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++
  • 26. 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++
  • 27. 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++ See D&D Fig 27.3
  • 28. 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 Exception Handling in C++ Optional!
  • 29. 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++
  • 30. 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++
  • 31. 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++
  • 32. 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++
  • 33. 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++
  • 34. 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++
  • 35. 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++
  • 36. Fig. 27.11 | Standard Library exception classes. Exception Handling in C++
  • 37. 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++
  • 38. Exception Handling Summary (continued) Many more details — see Deitel & Deitel Any other textbook C++ standard Exception Handling in C++