Error Raise
Assertion: Must #include "assert.h"
. If assertion fails, then program abort. We should avoid to use assert
, because it leaves no chance to programer to recover.
Remove preprocessor( assertion ) from code during compiling: g++ -DNDBUG
.
Exception Handle
When an error occurs deep in a call stack. If the error can’t be handled, then the entire program will be shut down. In order to avoid that, error handle is important to let program recover when catches the error.
Exception: An exception is an object thrown to represent the occurrence of an error. In C++, catch-try syntax is applied.
BDP: self-defined package exceptions and store exception object on the heap. All exceptions are thrown by exception classes.
Rational ADT Example:
1 | class Rational{ |
BDP: Keep exception-safe statements out of the rry-block for optimal performance, such as moving “cout <<” out of try
, and keep “cin >>” inside of try
.
Throw Exception
Rethrowing: when nearest up layer function can’t handle this exception, then throw another exception in order to pass this exception to function()
up the call stack by one layer.
1 | catch(someException &e) { cout << "Exceptioin caught" << e << endl; throw;} |
If destructor
throws an exception that is not handled locally, the program terminates. Because deconstructor always manages the memory.
After throw
, the program will not continue executing other lines.
noexcept Keyword:
1 | ~ Rational() noexcept; |
C++ 11 exception example:
1 | class Rational final{ |
Explaination: When input zero denominator, an exception is throwed from Rational
constructor, then catch this exception in main function
to do what you want. You may just print some reminder message on screen then abort this program, or use a while loop to recover this exception until correct input format.
Further example:
1 | int main(int argc, char** argv){ |
Running result:
1 | constructor called. |
Explaination: If we don’t stop program immediately after exception, then the exception raises but continues executing until c = a + b
, the program aborts. Because c = a + b
invokes Rational constructor
, exception is raised in the constructor, it happens on the top layer, so our program stops immediately. As the constructor we defined above, Under this situcaiton, a
and b
have been modified before throw
and passed to c
, this is bad. So for BDP, we shouldn’t assgin num
and denomin
to a
and b
before we know they are legal. It can changed to below code:
1 | Rational::Rational(int num, int denom) throw (const char*){ |
Running result:
1 | constructor called. |
Standard Exception example in C++
Resource Acquisition is Initialization (RAII). Equates resource management with the lifetime of an object
Reference material:
Book: Thinking in C++, Volume 1, 2nd Edition, Bruce Eckel.
Lectures: University of Waterloo, CS 247 (Software Abstraction and Specificati), 2020 spring term, professor Scott Chen.