π Lecture 43 β Techniques for Error Handling
π Overview: This lecture explores various error handling techniques in programming, ranging from basic abnormal termination to sophisticated exception handling. Understanding these methods is crucial for building robust, fault-tolerant applications that can gracefully recover from runtime errors without losing data.
ποΈ Topics Covered
The lecture covers five error handling techniques: abnormal termination, graceful termination, returning illegal values, returning error codes, and exception handling. It examines the limitations of traditional error handling approaches, including increased code complexity and mixing of error handling with program logic. The major focus is on exception handling using try, catch, and throw mechanisms, demonstrating how to separate main program logic from error handling code through custom exception classes and proper catch handler organization.
π Lecture Summary
Techniques for Error Handling
Programs may terminate abnormally or crash due to incorrect memory access, input/output errors, program faults, or external resource errors. Without error handling, work can be lost (e.g., text editor closing without saving). Five techniques are used: abnormal termination, graceful termination, return illegal value, return error code, and exception handling.
43.1. Example β Abnormal Termination
In abnormal termination, the program does nothing when an error occurs and is terminated abnormally by the operating system without saving data. The example shows a division by zero causing the program to crash.
void GetNumbers(int &a, int &b) { ... }
int Quotient(int a, int b) { return a / b; }
π Example: When user enters 10 and 0, output shows: "Program terminated abnormally" after displaying "Enter two integers".
43.2. Graceful Termination
Graceful termination uses if conditions to check for expected errors and performs clean-up tasks before exiting, preventing resource wastage.
int Quotient(int a, int b) {
if(b == 0) {
cout << "Denominator can't be zero" << endl;
exit(1); // clean exit with error code
}
return a / b;
}
π Example: Output shows "Denominator can't be zero" instead of abnormal termination.
43.3. Error Handling
a. Return Illegal Value
The clean-up tasks are of local nature only, and information loss remains possible. The programmer changes the value to prevent crash but puts program in inconsistent state.
int Quotient(int a, int b) {
if(b == 0)
b = 1; // illegal value substitution
OutputQuotient(a, b, a/b);
return a / b;
}
π Example: Input 10 and 0 shows "Quotient of 10 and 1 is 1" β wrong result, program continues in inconsistent state.
b. Return Error Code
Programmer avoids system crash but the program is now in an inconsistent state. The function returns a boolean to indicate success or failure.
bool Quotient(int a, int b, int &retVal) {
if(b == 0) return false;
retVal = a / b;
return true;
}
π Example: When denominator is zero, user is prompted repeatedly: "Denominator can't be Zero. Give input again" until a valid input is provided.
π‘ Why this matters: Error codes pollute function interfaces and force callers to check return values, which they might ignore.
Issues in Error Handling
Traditional error handling creates several problems:
- Programmer must change design to incorporate error handling
- Must check return type of function to detect errors
- Calling function can ignore return value
- Function result might contain illegal value, causing later system crash
- Program complexity increases β error handling code mixes with program logic, code becomes less readable and difficult to modify
π Example comparison: Without error handling: function1(); function2(); function3(); which is clean and simple. With error handling: Nested if-statements checking each function's return value, creating deeply nested, hard-to-read code.
43.4. Exception Handling
Exception handling is a much more elegant solution compared to other error handling mechanisms. It enables separation of main logic and error handling code, keeping program flow clean.
43.5. Exception Handling Process
- Code suspected to cause an exception is written in try block
- Code encountering an error throws an object representing the exception
- Catch blocks follow the try block to catch thrown objects
Syntax β Throwing an Exception
The keyword throw is used to throw an exception. Any expression can represent the exception. Examples:
throw 1; // literal constant
throw (a); // variable
throw obj; // object
throw Exception(); // anonymous object
throw 1+2*9; // mathematical expression
π Definition β Exception Object: Primitive data types should be avoided as throw expressions due to ambiguity. Define new classes to represent exceptions β this reduces ambiguity.
Syntax β Try and Catch
try {
// code that may throw exception
}
catch (Exception1) { ... } // caught if exception was thrown
catch (Exception2 obj) { ... } // caught if exception was thrown
Catch Rules:
- Catch handler must be preceded by a try block or another catch handler
- Catch handlers only execute when exception occurs
- Differentiated on basis of argument type
- Tried in order written
- Work like switch statements without needing
break
Complete Example of try, catch, and throw
class DivideByZero {
public:
DivideByZero() {}
};
int Quotient(int a, int b) {
if(b == 0) {
throw DivideByZero(); // throw class object as exception
}
return a / b;
}
Main program with try-catch:
for(int i = 0; i < 10; i++) {
try {
GetNumbers(a,b);
quot = Quotient(a,b);
OutputQuotient(a,b,quot);
sum += quot;
}
catch(DivideByZero) {
i--;
cout << "\nAttempt to divide numerator with zero";
}
}
π Output when denominator is zero: "Attempt to divide numerator (dividend) with zero" β program continues normally for remaining iterations.
Catch Handler
The catch handler catches the DivideByZero exception through an anonymous object. Program logic and error handling code are now separated cleanly.
π‘ Why this matters: The object can be modified to carry information about the cause of the error, making error reporting more detailed.
Separation of Program Logic and Error Handling
With exception handling, the main program logic remains clean and simple:
try {
function1();
function2();
function3();
}
catch(ErrorX) { ... }
catch(ErrorY) { ... }
catch(ErrorZ) { ... }
The error handling code is now completely separate from the business logic, making code more readable, maintainable, and easier to modify.
β Key Takeaways
Exception handling is the most elegant error handling technique because it completely separates error handling logic from main program flow, unlike other methods that mix concerns and increase complexity. The try block contains code that might fail, the throw statement sends an exception object (preferably a custom class, not primitive types) when an error occurs, and catch blocks handle specific exception types in order of declaration. Return error codes and illegal values force programmers to change function interfaces and check return values, while abnormal termination loses all data without cleanup. Using dedicated exception classes instead of primitive types prevents ambiguity and allows carrying rich error information.
π§ Quick Revision Questions
- What are the five error handling techniques discussed, and what is the main disadvantage of the first four compared to exception handling?
- Why should primitive data types be avoided when throwing exceptions, and what should be used instead?
- In the graceful termination example, what keyword is used to exit the program after performing cleanup?
- How does exception handling improve code readability compared to return error codes?
- What determines which catch block executes when multiple catch blocks follow a try block?
π Lecture 44 β Stack Unwinding in Exception Handling
π Overview: This lecture examines what happens to local variables when exceptions are thrown, introducing the concept of stack unwindingβhow try-catch blocks are unwound during nested function calls or nested try-catch blocks. It also covers catch handler behavior, inheritance of exceptions, re-throwing, and the order of handlers.
ποΈ Topics Covered
Stack unwinding with nested try-catch blocks and nested functions; destruction of local objects and dynamically allocated memory during exceptions; examples of stack unwinding with function calls and nested blocks; catch handler modifications to carry error information; passing exceptions by reference; destruction of exception objects; avoiding too many catch handlers using inheritance; catching every exception with catch(...); re-throwing exceptions for partial handling; and the order of handlers.
π Lecture Summary
Previous Lecture Example of Exception Handling
This lecture begins with a review example showing the DivideByZero exception class and the Quotient function that throws this exception when the divisor is zero. The main function uses a try-catch block to call Quotient and catch the DivideByZero exception.
Now, we want to see what happens to local variables in a try block when an exception is thrown; this concept is called stack unwinding, which tells how try-catch blocks are unwound (executed) when there are nested function calls involving try-catch blocks or nested try-catch blocks themselves.
44.1.Stack Unwinding
The flow control (the order in which code statements and function calls are made) as a result of throw statement is referred to as "stack unwinding".
Stack unwinding can take place in the following two ways:
- Nested try-catch blocks (one try-catch block inside another):
try {
try {
// code
} catch(Exception e) {
// handler
}
} catch(exception e) {
// handler
}
- Exception thrown from nested functions having try-catch blocks:
void function1() {
throw Exception();
}
void function2() {
function1();
}
int main() {
try {
function2();
} catch(Exception) { }
return 0;
}
Stack unwinding is more complex than simple nested function calls (or recursive function calls) as in the case of nested try-catch blocks, exceptions can be thrown from any try block, so transfer of control to catch handler is complex.
First note these points:
- β All the local objects of an executing block are destroyed when an exception is thrown
- β Dynamically allocated memory is not destroyed automatically
- β If no catch handler catches the exception, the function terminate is called, which by default calls function abort
β Examples β
Nested Functions example:
In the example below, we have two functions function1 and function2; function2 calls function1. In function1 we have added exception throwing code, so it is necessary to call function1 in try-catch blocks; otherwise the compiler will generate an error. We call function2 in main; note that function2 itself calls function1 that needs a try-catch block, so we need to call function2 in a try-catch block. In case function1 code generates an exception, stack unwinding takes place: control will be returned to function2 which will return control to main.
main() -> function2() -> function1() throws exception
β
main() β function2() β (stack unwinding occurs)
Nested Try-catch blocks example: Stack unwinding is also performed if we have nested try-catch blocks:
int main() {
try {
try {
throw 1;
}
catch(float) { }
}
catch(int) {
}
return 0;
}
π Example β Stack Unwinding Order:
-
If exception is thrown from the innermost try block:
- Firstly, the catch handler with float parameter is tried (innermost); this catch handler will not be executed as its parameter is of a different type β no coercion (match)
- Secondly, the catch handler with int parameter is tried and executed
-
If exception is thrown from the outer try block, there is no other try block above it, so only this block's catch handler will be matched with the exception. If it matches, the catch block is executed; otherwise, the default terminate and abort functions will be called.
Catch Handler
- We can modify the code in the catch handler to use the exception object to carry information about the cause of error
- The exception object thrown is copied to the object given in the handler
- We pass the exception by reference instead of by value in the catch handler to avoid problems caused by shallow copy
Example:
We have added a method Print in our exception class to show the user the cause of error:
class DivideByZero { // exception class
int numerator;
public:
DivideByZero(int i) { // constructor taking one parameter (dividend)
numerator = i;
}
void Print() const {
cout << endl << numerator << " was divided by zero";
}
};
int Quotient(int a, int b) {
if(b == 0) {
throw DivideByZero(a);
}
return a / b;
}
for (int i = 0; i < 10; i++) {
try {
GetNumbers(a, b);
quot = Quotient(a, b);
// ...
} catch(DivideByZero & obj) {
obj.Print();
i--;
}
}
Output:
Enter two integers
10
10
Quotient of 10 and 10 is 1
Enter two integers
10
0
10 was divided by zero
...
π Catch Handler: The object thrown as exception is destroyed when the execution of the catch handler completes.
Avoiding too many Catch Handlers
There are two ways to catch more than one object in a single catch handler:
- Use inheritance
- Catch every exception
Inheritance of Exceptions
In inheritance, we group all exceptions according to their categories and catch a single exception for the whole category. For example, for code below we have divided the exceptions as follows:
- Math exceptions (DivideByZero and IntegerOutOfRange exception)
- Input Output exceptions (InputStreamError)
Without inheritance:
try {
// ...
}
catch(DivideByZero) { ... }
catch(IntegerOutOfRange) { ... }
catch(InputStreamError) { ... }
Example β With Inheritance:
try {
// ...
}
catch(MathError) { }
catch(InputStreamError) { }
By using a base class MathError for both DivideByZero and IntegerOutOfRange, we can catch them both with a single catch(MathError) handler.
Catch Every Exception
C++ provides a special syntax that allows catching every object thrown:
catch(...) {
// ...
}
Re-Throw
A function can catch an exception and perform partial handling. Re-throw is a mechanism of throwing the exception again after partial handling:
throw; /*without any expression*/
Example:
void Function() {
try {
/*Code that might throw an Exception*/
}
catch(Exception&) {
if(can_handle_completely) {
// handle exception
} else {
// partially handle exception
throw; //re-throw exception
}
} // end of catch
} // end of function
int main() {
try {
Function();
}
catch(Exception&) {
// ...
}
return 0;
}
Order of Handlers
The order of more than one catch handlers can cause logical errors when using inheritance or catch all (although the compiler will not generate any error in this case):
try {
// ...
}
catch(...) { } // catches EVERYTHING
catch(MathError) { ... }
catch(DivideByZero) { ... }
// last two handlers can NEVER be invoked
// as general exception class will catch all exceptions
// including the next two
π‘ Why this matters: The last two handlers (MathError and DivideByZero) can never be invoked because the catch(...) handler catches all exceptions first, making subsequent handlers unreachable. Always place more specific handlers before more general ones.
β Key Takeaways
Stack unwinding is the process of destroying local objects and returning control through nested function calls or nested try-catch blocks when an exception is thrown. All local objects in an executing block are destroyed, but dynamically allocated memory must be manually freed. Catch handlers can receive exception objects by reference to avoid shallow copy problems, and the exception object is destroyed when the handler completes. To avoid too many catch handlers, use inheritance (group related exceptions under a base class) or the catch(...) syntax to catch all exceptions. When using inheritance or catch-all handlers, always order them from most specific to most general; otherwise, more specific handlers will never execute. Re-throwing (throw; without an expression) allows partial handling of an exception before passing it up the call stack.
π§ Quick Revision Questions
- What is stack unwinding, and in what two situations does it occur?
- What happens to local objects and dynamically allocated memory when an exception is thrown?
- Why should exception objects be passed by reference rather than by value in a catch handler?
- What are the two techniques to reduce the number of catch handlers in a program?
- If you place
catch(...)before a more specific handler likecatch(MathError), what will happen, and why?
π Lecture 45 β Resource Management
π Overview: This lecture focuses on managing resources in C++ in the presence of exceptions, including proper resource release, exceptions in constructors and destructors, and exception specifications. It concludes with a comprehensive course review covering all major topics from Object Orientation to Exception Handling.
ποΈ Topics Covered
The lecture covers resource management techniques when exceptions occur, including methods to ensure file resources are properly released, exception handling in constructors (including initialization lists), rules for exceptions in destructors, exception specification syntax and behavior, and ends with a full course review of Object Oriented Programming concepts.
π Lecture Summary
45.1. Resource Management
A function that acquires a resource must properly release it. Throwing an exception can cause resource wastage because the code to release the resource may be skipped.
π Definition β Resource Management: The practice of ensuring that acquired resources (like file handles, memory) are properly released, even when exceptions occur.
π Example β Without proper management:
int function1(){
FILE *fileptr = fopen("filename.txt","w");
// ...
throw exception();
// ...
fclose(fileptr); // This line is never reached if exception is thrown
return 0;
}
In case of exception, the call to fclose will be ignored and the file will remain opened.
First Attempt β Using try-catch:
int function1(){
try{
FILE *fileptr = fopen("filename.txt","w");
fwrite("Hello World",1,11,fileptr);
// ...
throw exception();
fclose(fileptr);
} catch(...) {
fclose(fileptr); // adding fclose in catch handler as well
throw;
}
return 0;
}
But this results in code duplication.
Second Attempt β Using a separate class:
class FilePtr{
FILE * f;
public:
FilePtr(const char *name, const char * mode) {
f = fopen(name, mode);
}
~FilePtr() {
fclose(f);
}
operator FILE * () {
return f;
}
};
int function1(){
FilePtr file("filename.txt","w");
fwrite("Hello World",1,11,file);
throw exception();
// ...
return 0;
}
The destructor of the FilePtr class will close the file. The programmer does not have to close the file explicitly in case of error as well as in normal case. Objects and local variables in try block are destroyed automatically when try block completes its execution or in case exception is thrown, so this file object will automatically be destroyed.
π‘ Why this matters: This pattern (Resource Acquisition Is Initialization - RAII) ensures automatic resource cleanup regardless of how the block is exited, making code safer and simpler.
Exception in Constructors
An exception thrown in a constructor causes the destructor to be called for any object built as part of the object being constructed before the exception is thrown. However, the destructor for the partially constructed object itself is not called.
π Example:
class Student{
String FirstName;
String SecondName;
String EmailAddress;
// ...
};
If the constructor of SecondName throws an exception, then the destructor for FirstName will be called. Generally, if an exception is thrown in a constructor, all objects created so far are destroyed. If EmailAddress String object had thrown an exception, then SecondName and FirstName objects will be destroyed using their destructors. However, the destructor of the Student class itself will not be called in any case, as its object was not completely constructed.
π Definition β Partially Constructed Object: An object whose constructor did not complete execution due to an exception. Its destructor is not called.
Exception in Initialization List
An exception due to the constructor of any contained object or the constructor of a parent class can be caught in the member initialization list.
π Example:
Student::Student (String aName) : name(aName)
/*The constructor of String can throw a exception*/
{
// ...
}
The programmer may want to catch the exception and perform some action to rectify the problem:
Student::Student (String aName)
try : name(aName) {
// ...
}
catch(...) {
}
π Definition β Function-try-block: A try block that encloses the entire function body, including the member initialization list, allowing exceptions from constructors of base or member objects to be caught.
Exceptions in Destructors
An exception should not leave the destructor. When a destructor is running, it means there is a stack unwinding process going on that has run this destructor to delete this object. If this exception is allowed to propagate, it will run another stack unwinding mechanism, which is not allowed. C++ allows running only one stack unwinding process at a time.
If a destructor is called due to stack unwinding, and an exception leaves the destructor, then the function std::terminate() is called, which by default calls std::abort().
π Example β Incorrect:
class Complex{
// ...
public:
~Complex(){
throw Exception();
}
};
int main(){
try{
Complex obj;
throw Exception();
// ...
}
catch(...){
}
return 0;
}
// The program will terminate abnormally
β Solution β Catch the exception inside the destructor itself:
Complex::~Complex()
{
try{
throw Exception();
}
catch(...){
}
}
In this case, a single stack unwinding process may handle the situation.
π Definition β std::terminate(): A function called when the exception handling mechanism cannot find a handler for a thrown exception, or when an exception propagates out of a destructor during stack unwinding. It typically terminates the program.
Exception Specification
A program can specify the list of exceptions a function is allowed to throw. This list is also called a throw list. If we write an empty list, the function won't be able to throw any exception.
π Syntax:
void Function1() {...} // Can throw any exception
void Function2() throw () {...} // Cannot throw any exception
void Function3() throw (Exception1, ...){} // Can throw Exception1 or derived types
Here:
Function1can throw any exception.Function2cannot throw any exception.Function3can throw any exception of typeException1or any class derived from it.
If a function throws an exception other than those specified in the throw list, the function unexpected is called, which in turn calls terminate and terminates the program. If the programmer wants to handle such cases, they must provide a handler function and tell the compiler to call that handler using set_unexpected.
π Definition β Exception Specification (throw list): A C++ feature that declares which exception types a function may throw. Violating this specification calls std::unexpected().
Course Review
The course covered the following major topics:
Object Orientation:
- What is an object
- Object-Oriented Model: Information Hiding, Encapsulation, Abstraction
- Classes
Object Orientation (continued):
- Inheritance: Generalization, Sub-Typing, Specialization
- "IS-A" relationship
- Abstract classes
- Concrete classes
Object Orientation (continued):
- Multiple inheritance
- Types of association: Simple association, Composition, Aggregation
- Polymorphism
Classes β C++ Constructs:
- Classes: Data members, Member functions
- Access specifier
- Constructors
- Copy Constructors
- Destructors
Classes β C++ Constructs (continued):
thispointer- Constant objects
- Static data member
- Static member function
- Dynamic allocation
Classes β C++ Constructs (continued):
- Friend classes
- Friend functions
- Operator overloading: Binary operator, Unary operator, operator[], Type conversion
Inheritance β C++ Constructs:
- Public inheritance
- Private inheritance
- Protected inheritance
- Overriding
- Class hierarchy
Polymorphism β C++ Constructs:
- Static type vs. dynamic type
- Virtual function
- Virtual destructor
- V-tables
- Multiple inheritance
- Virtual inheritance
Templates β C++ Constructs:
- Generic programming
- Classes template
- Function templates
- Generic algorithm
- Templates specialization: Partial Specialization, Complete specialization
Templates β C++ Constructs (continued):
- Inheritance and templates
- Friends and templates
- STL: Containers, Iterators, Algorithms
Writing Reliable Programs:
- Error handling techniques: Abnormal termination, Graceful termination, Return the illegal value, Return error code from a function, Exception handling
β Key Takeaways
Resource management with RAII (using class destructors to release resources) is the safest way to handle exceptions as it ensures automatic cleanup without code duplication. Exceptions in constructors cause destruction of fully constructed sub-objects but not the partially constructed object itself; use function-try-blocks to catch exceptions from initialization lists. Exceptions must never leave a destructor, especially during stack unwinding, as this will call std::terminate(). Exception specifications (throw lists) declare what exceptions a function may throw, and violating them triggers std::unexpected(). The course review confirms that object orientation, inheritance, polymorphism, templates, STL, and exception handling are all interconnected tools for building reliable C++ programs.
π§ Quick Revision Questions
- What happens to the file handle in the first example when an exception is thrown before
fclose()is called, and how does the RAII approach withFilePtrsolve this? - If a constructor for
Studentcontains threeStringmember objects and the constructor for the third member throws, which destructors are called and why isn'tStudent's destructor called? - What is the behavior when an exception propagates out of a destructor that was already called during stack unwinding from another exception?
- How would you write a function that is guaranteed to throw no exceptions using an exception specification?
- What function is called if a function throws an exception not listed in its throw list, and what is the default behavior?