1 / 19

Advanced Program Design with C++

Advanced Program Design with C++. Part 10: Exception handling. Exception handling: introduction. Programs are meant to work correctly within their specifications . However, a program might be faced with unforeseen circumstances that are outside of its specifications.

Télécharger la présentation

Advanced Program Design with C++

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Advanced Program Design with C++ Part 10: Exception handling Joey Paquet, 2007-2014

  2. Exception handling: introduction • Programs are meant to work correctly within their specifications. • However, a program might be faced with unforeseen circumstances that are outside of its specifications. • Unforeseen situations may come: • Externally from the environment of the program • When a user or software client tries to use the software outside of its specified usage characteristics. • When the program tries to use another piece of software and is faced with unforeseen behavior. • Internally from its own execution • When the program misbehaves due to an internal logical error and/or being in an inconsistent state. • A robust program should be able to handle all kinds of circumstances, foreseen or unforeseen, whether they are coming from the exterior or are a result of its own faults. Joey Paquet, 2007-2014

  3. Exception handling: introduction • Exception handling is a mechanism that allows two separately developed program components to communicate when a program anomaly is encountered during the execution of the program. • Such communication upon erroneous behavior has been long part of programming practice in the form of error codes and error handling. • In error handling, functions set or return special error codes in case of malfunction and finish execution normally. • It is then assumed that any function that might be affected will use the error code and react by handling the error i.e. to continue normal execution despite the error. Joey Paquet, 2007-2014

  4. Exception handling: example C programs with error handling #include<stdio.h> #include<errno.h> #include<string.h> externinterrno; int main() { FILE * pf; interrnum; pf = fopen("unexist.txt", "rb"); if (pf == NULL) { errnum = errno; fprintf(stderr, "Value of errno: %d\n", errno); perror("Error printed by perror"); fprintf(stderr, "Error opening file: %s\n", strerror(errnum)); } else{ fclose(pf); } return 0; } #include<stdio.h> #include<stdlib.h> main() { int dividend = 20; int divisor = 5; int quotient; if (divisor == 0){ fprintf(stderr, "Division by zero! Exiting...\n"); exit(EXIT_FAILURE); } quotient = dividend / divisor; fprintf(stderr, "Value of quotient : %d\n", quotient); exit(EXIT_SUCCESS); } Joey Paquet, 2007-2014

  5. Exception handling: introduction • However, error handling introduce confusion as it does not enable to separate normal behavior from error-handling behavior. • To be more structured, functions should be first programmed according to the specifications of their normal behavior, and clearly separate code should be provided for abnormal cases, i.e. cases outside of the function’s specifications of normal behavior. Joey Paquet, 2007-2014

  6. Exception handling: introduction • The first programming language to provide the early concept of exception handling was LISP in the early 1960. PL/1 later extended the concept in the early 1970s. • An exception is a data structure that is generated when a special erroneous condition is met, that contains information about the nature and context of this erroneous condition. • Exceptions are processed by an exception handling mechanism that only takes effect when an exception has been identified. • The exception handling mechanism will then take over the normal execution mechanism until the exception is resolved. • If the exception can be properly resolved, normal execution is resumed. • If the exception cannot be resolved, the program execution is terminated. Joey Paquet, 2007-2014

  7. Exception handling: try-throw-catch • Syntactically, handling exceptions in C++ is made through of the try-throw-catchkeyword trio, which is highly similar to what is used in Java. • The try block contains a part of the code for the normal execution of the program. • It is called a try block because it triesto execute the normal execution behavior, but where something is likely to be subject to exceptionally erroneous behavior. Code that will/should not throw any exception try { CodeThatMayThrowAnException } Code that will/should not throw any exception Joey Paquet, 2007-2014

  8. Exception handling: try-throw-catch • Whenever a piece of code identifies an exceptionally wrong situation, it can create an exception and trigger the exception handling mechanism by using a throw statement: throw value Or more specifically throw new ExceptionClassName(PossiblySomeArguments); • When an exception is thrown, the normal execution of the surrounding try block is stopped and the exception handling mechanism takes over the execution of the program. • Normally, the flow of control is transferred by the exception handling mechanism to another portion of code known as a catch block. • The value thrown is the argument to the throw operator, and can be any value (possibly an instance of some exception class). Joey Paquet, 2007-2014

  9. Exception handling: try-throw-catch • A throw statement is similar to a method call: throw new ClassName(“Some Descriptive String”); • In the above example, an object of class ClassName is created using a string as its argument (assuming that it has such a constructor defined) and used as an exception object. • Unlike Java, C++ can use any value as an exception, and classes used to instantiate exceptions do not need to be subclasses of the standard exception class. • The throw statement has the effect of temporarily halting the normal execution of the program and handing it over to the exception handling mechanism. Joey Paquet, 2007-2014

  10. Exception handling: try-throw-catch • When an exception is thrownand the exception handling mechanism takes over, it tries to find a corresponding catch block to handle the exception. • Acatch block has at most one parameter. • The exception object thrown is passed to the catchblock using a similar mechanism as for a function call’s parameter passing. • The type of the catch block’s exception object parameter determines what kind of exception a catch block is meant to handle. • The execution of the catch block is called catching the exception, or handling the exception. catch(Exception e) { ExceptionHandlingCode } Joey Paquet, 2007-2014

  11. Exception handling: try-throw-catch • Any catch block is attached to a specific try block. • A catch block is an exception handler that is meant to handle some exception thrown in the try block it is attached to. • The type of exception it is meant to handle is specified by its parameter type. • A single try block can be attached to as many catch blocks as there are different kinds of exceptions potentially thrown in the try block’s code. • A catch block mean to catch all exceptions is signified using an ellipse (…) as a parameter. try { // Code that potentially throws some exception(s) } catch (ExceptionType1 e){ // Exception handling code for ExceptionType1 } catch (ExceptionType2 e){ // Exception handling code for ExceptionType1 } catch (...){ // Exception handling code for any other type of // exception not handled by the preceding catch blocks } Joey Paquet, 2007-2014

  12. Exception handling: try-throw-catch • When a try block is executed, three things can happen: • No exception is thrown in the try block • The code in the try block is executed to the end of the block. • The catch blocks are skipped. • The execution continues with the code placed after the catch block. • An exception is thrown in the try block and caught in a catch block • The rest of the code in the try block is skipped. • Control is transferred to a following catch block. • The thrown object is passed to the catch block using parameter passing. • The code in the catch block is executed. • Normal execution resumes using the code that follows all catch blocks. • An exception is thrown in the try block and there is no corresponding catch block to handle the exception • The rest of the code in the try block is skipped. • The function throws the exception to its calling function. • The calling function either catches the exception using a catch block, or throws the exception to its calling function. • If all the called functions fail to catch the exception, the exception will eventually be thrown all the way to the main function. • If the main function cannot catch the exception, the program ends, itself throwing the exception. Joey Paquet, 2007-2014

  13. Exception handling: stack unwinding • Once the exception handling mechanism takes control as a throw statement is executed, control moves from the throw statement to the first catch statement that can handle the thrown type. • Once the control goes to the catch handler, a process known as stack unwinding is used to delete all the automatically allocated local variables that were used between the execution site where the exception was thrown and the execution site where the exception is caught. void g(){ // to be deleted first during stack unwinding // including parameters passed as value throwstd::exception(); } void f(){ // to be deleted second during stack unwinding // including parameters passed as value g(); } int main(){ // not to be deleted during stack unwinding try{ // to be deleted third during stack unwinding f(); } catch(...){ } // resume here after handling } Joey Paquet, 2007-2014

  14. Exception handling: stack unwinding • If exceptions are thrown in constructors, only the parts of the object that were yet fully constructed are destructed during stack unwinding. charclassToThrow; classD { public: D(){ cout<< "Constructor D()" << endl; if(classToThrow == 'D') throwclassToThrow; } ~D(){ cout << "Destructor ~D()" << endl; } }; class C { public: C(){ cout<< "Constructor C()" << endl; if(classToThrow == 'C') throwclassToThrow; } ~C(){ cout << "Destructor ~C()" << endl; } }; class B { public: B(){ cout<< "Constructor B()" << endl; if(classToThrow == 'B') throwclassToThrow; } ~B(){ cout << "Destructor ~B()" << endl; } }; class A : public B { public: C mC1; D mD2; A() { cout << "Constructor A()" << endl; if (classToThrow == 'A') throwclassToThrow; } ~A(){ cout << "Destructor ~A()" << endl; } }; int main(){ while (true){ cout << "Enter a class name : "; cin >> classToThrow; try{ A* a = new A(); delete a; } catch (char c){ cout << "catching " << c << endl; } } system("PAUSE"); return EXIT_SUCCESS; } Joey Paquet, 2007-2014

  15. Exception handling: exception specification • Exception specifications: throw clause • Does not mean that the code executed by the function is guaranteed to throw only exception listed in its throw list. • Rather, it means that the exception handling mechanism will make the program call unexpected() if a function throws an exception type that in not listed in its throw clause. • The default behavior of unexpected() is to call terminate(), which abruptly stops the program’s execution. • This verification is only used at runtime. The compiler will not verify that all exceptions potentially thrown by the code included in a function only throw exceptions listed in its throw list. • Exception specification has been eliminated in C++11. • http://en.wikibooks.org/wiki/C%2B%2B_Programming/Exception_Handling • http://www.gotw.ca/publications/mill22.htm • http://www.informit.com/guides/content.aspx?g=cplusplus&seqNum=109 Joey Paquet, 2007-2014

  16. Exception handling: re-throwing Joey Paquet, 2007-2014

  17. Exceptions: overhead • The exception mechanism has a very minimal performance cost if no exception is thrown. If an exception is thrown, the cost of the stack traversal and unwinding is roughly comparable to the cost of a function call. Additional data structures are required to track the call stack after a try block is entered, and additional instructions are required to unwind the stack if an exception is thrown. However, in most scenarios, the cost in performance and memory footprint is not significant. The adverse effect of exceptions on performance is likely to be significant only on very memory-constrained systems, or in performance-critical loops where an error is likely to occur regularly and the code to handle it is tightly coupled to the code that reports it. In any case, it's impossible to know the actual cost of exceptions without profiling and measuring. Even in those rare cases when the cost is significant, you can weigh it against the increased correctness, easier maintainability, and other advantages that are provided by a well-designed exception policy. • http://msdn.microsoft.com/en-us/library/hh279678.aspx Joey Paquet, 2007-2014

  18. Exception handling: significance • So, does the exception handling mechanism solve our error handling problems? No, it is only a mechanism. Does the exception handling mechanism provide a radically new way of dealing with errors? No, it simply provides a formal and explicit way of applying the standard techniques. The exception handling mechanism • [1] Makes it easier to adhere to the best practices. • [2] Gives error handling a more regular style. • [3] Makes error handling code more readable. • [4] Makes error handling code more amenable to tools. • http://www.stroustrup.com/except89.pdf Joey Paquet, 2007-2014

  19. References • http://www.tutorialspoint.com/cplusplus/cpp_exceptions_handling.htm • http://msdn.microsoft.com/en-us/library/vstudio/4t3saedz(v=vs.100).aspx • http://en.wikibooks.org/wiki/C%2B%2B_Programming/Exception_Handling • http://www.stroustrup.com/except89.pdf • http://www.informit.com/articles/article.aspx?p=31537 • http://www.tutorialspoint.com/cprogramming/c_error_handling.htm • Goodenough, John B. Structured exception handling. Proceedings of the 2nd ACM SIGACT-SIGPLAN symposium on Principles of programming languages - POPL '75. pp. 204–224. doi:10.1145/512976.512997 • http://msdn.microsoft.com/en-us/library/hh254939.aspx Joey Paquet, 2007-2014

More Related