Traditional Approaches
- Let Run-Time Environment Abort the Program
- Ask Run-Time Environment to Abort the Program
- Use Error Checking
- Using Function Return Value for Error Checking
Traditional Approaches
Problems with Traditional Approaches
In the exception handling approach, the run-time error is detected, but the program handles the error and aborts the program only if necessary
The code to detect and handle errors has a standard pattern that must be followed, and every C++ programmer should know how to handle it
Try-Catch Block
The exception handling is built upon 3 keywords: try, catch, and throw
Exception is an issue that arises during the execution of any program
The try clause detects the possibility of error and throws an exception object
The catch clause handles the exception to prevent abortion
The two clauses must be one after the other without any code in between; they belong to the same block
There are three patterns commonly used with exception handling approaches
The try-catch block is completely contained in one function
If an exception is thrown, the rest of the try clause after the throw statement is ignored and control moves to the catch clause
The function continues after the catch clause unless the program is aborted in the catch clause
The try-catch block is still in main, but the exception is thrown in another function that is called in the try clause. The throw statement in this case is in the called function
When an exception is thrown, the rest of the code in the called function is ignored and the program flow moves to the catch block in the calling function
We have only one actual throw statement, which is enclosed in its own try block
The second throw statement simply rethrows the previous one
Queries about this Lesson, please send them to:
*References*
- C++ Programming - An Object-Oriented Approach, 2019
Behrouz, Richard et.al
- Accelerated C++ - Practical Programming by Example, 2000
Andrew, Barbara et.al
Courtesy of …