Lecture 31 Exception Handling
Lecture 31 Exception Handling
Session No.: 31
Course Name: OOPS with C++
Course Code: E1UA203C
Instructor Name: Dr. Pijush Kanti Dutta Pramanik
Duration: 50 Mins
Date of Conduction of Class: 8.6.25
1
Can you think of a time when your program crashed
unexpectedly?
2
Review of Previous Session
3
By the end of this lesson, you should be able to:
5
What is an Exception?
• Examples:
• Division by Zero: Attempting to divide a number by zero
causes a runtime error.
• Invalid User Input: Input that doesn't meet expected criteria
can lead to exceptions.
• File Not Found: Trying to access a file that doesn't exist
generates an error.
The Need for Exception
Handling
• Error Management: Prevent program crashes by catching errors before
they propagate.
Purpose: The try block contains code that might throw an exception.
Syntax:
try
{
// Code that may throw an exception
}
Example:
try
{
// Some risky operation
}
9
• If an exception occurs here, control jumps to the corresponding catch block.
The throw Statement
Syntax:
throw exception_object; // Throwing an exception
Example:
throw "Division by zero error"; // Throwing a string exception
The catch Block
pose: The catch block is responsible for handling exceptions thrown by the try blo
tax:
ch (ExceptionType e)
mple:
ch (const char* msg)
err << "Error: " << msg << endl; // Handling the exception
13
Example of User-Defined
class MyException : public Exception
int main()
std::exception {
{ try {
public: riskyFunction(); // Call that may throw an
const char* what() const noexcept exception
override }
{ catch (const MyException& e)
return "My custom exception {
occurred"; // Error message std::cerr << e.what() << std::endl; //
} Handling the custom exception
}; }
return 0;
void riskyFunction() }
{
throw MyException(); // Throwing a
• Custom Class: MyException inherits from std::exception and overrides the what() method to provide a
user-defined exception
custom error message.
•} Throwing and Catching: The riskyFunction throws MyException, which is caught in main. The custom
14
message is displayed.
Best Practices for Exception
Handling
• Use Specific Exceptions: Catch specific exceptions before general ones to handle
different error types appropriately.
• Avoid Using catch (...): This catches all exceptions but loses type
information, making debugging difficult.
• Document Exceptions: Clearly document which functions can throw exceptions and
what types they may throw.
15
Exception Safety Levels
16
Example of Strong Guarantee
class SafeVector
{
private: Explanation:
std::vector<int> data; • Class Design: SafeVector
encapsulates a vector and
public: provides methods to add
void add(int value) and access elements safely.
{ • Error Handling: The get
data.push_back(value); // If this fails, the state remains method checks for out-of-
unchanged range access and throws an
} exception if the index is
invalid.
int get(int index) • Robustness: If an exception
{ occurs during push_back,
if (index >= data.size()) the existing state of the
{ vector remains unchanged.
throw std::out_of_range("Index out of range"); //
Throwing exception
} 17
return data[index];
Learning Activity 1
Error Scenario Brainstorm
1.Individually, students write down
three common programming
errors they have encountered or
can imagine (e.g., file not found,
null pointer dereference).
2.In pairs, students discuss their
errors and brainstorm how they
would implement exception
handling for each scenario.
3.They should identify potential
exceptions to be thrown and how
to catch them.
4.A few pairs present one error and wooclap.co
their proposed exception- m
Event code: 18
handling solution to the class.
Reflection- Learning Activity 1
Example Errors and Solutions
1.Error: Dividing by Zero
•Solution: Use exception handling to throw a std::invalid_argument exception if the
denominator is zero.
•Justification: This prevents the program from crashing and allows the user to receive
a meaningful error message, improving user experience.
2.Error: File Not Found
•Solution: Throw a std::runtime_error when an attempt to open a non-existent file
fails.
•Justification: Catching this exception allows the program to handle the error
gracefully, perhaps by prompting the user to check the file path or providing a default
action.
3.Error: Null Pointer Dereference
•Solution: Check if a pointer is null before dereferencing it, and throw a custom
exception if it is.
•Justification: This avoids undefined behavior and crashes, while the custom
exception can provide specific details about the error.
4.Error: Array Index Out of Bounds
•Solution: Check the index against the array size and throw an std::out_of_range
exception if the index is invalid.
•Justification: This allows the program to handle incorrect indexing without crashing,
Summary
20
Attainment of LOs in alignment to the learning
activities:
Galgotias University 23
Review and Reflection from
Students
24