0% found this document useful (0 votes)
6 views24 pages

Lecture 31 Exception Handling

This document outlines a session on Exception Handling in C++ as part of an OOPS course, focusing on implementing techniques using try, catch, and throw. It emphasizes the importance of exception handling for program stability and user experience, detailing standard and user-defined exceptions, best practices, and safety levels. The session also includes learning activities and assignments to reinforce the concepts discussed.

Uploaded by

ck1276295
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views24 pages

Lecture 31 Exception Handling

This document outlines a session on Exception Handling in C++ as part of an OOPS course, focusing on implementing techniques using try, catch, and throw. It emphasizes the importance of exception handling for program stability and user experience, detailing standard and user-defined exceptions, best practices, and safety levels. The session also includes learning activities and assignments to reinforce the concepts discussed.

Uploaded by

ck1276295
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 24

Exception Handling in C++

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?

What do you think could have been done to prevent


that crash, and how might exception handling play a
role in managing such situations?

2
Review of Previous Session

3
By the end of this lesson, you should be able to:

LO 1: Implement exception handling


techniques using try, catch, and
throw in C++.

LO 2: Analyze and create


custom exception classes to
manage specific error
conditions.
Galgotias University 4
Introduction to Exception
Handling

Definition: Exception handling is a mechanism to manage runtime errors in C++.

Importance: Ensures program stability and enhances user experience by preventing


crashes.

Goal: To provide a structured way to handle errors, improving the robustness of


applications.

5
What is an Exception?

• Definition: An unexpected event that disrupts the normal flow


of execution.

• 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.

• Controlled Flow: Maintain program stability by allowing recovery from


unexpected conditions.

• User Experience: Provide meaningful error messages to users instead of


abrupt crashes.
Basic Components

Exception Handling Keywords

• try: Encloses code that may throw an exception.

• catch: Handles exceptions thrown from the try block.

• throw: Signals that an exception has occurred.


The try Block

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

Purpose: The throw statement is used to signal an exception.

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)

Handle the exception

mple:
ch (const char* msg)

err << "Error: " << msg << endl; // Handling the exception

his block executes if an exception of the specified type is thrown. 11


Example of Basic Exception
Handling
int main()
void divide(int a, int b)
{ {
if (b == 0) try
{ {
throw "Division by zero error"; // divide(10, 0); // This will throw an
Throwing an exception exception
} }
cout << "Result: " << a / b << endl; catch (const char* msg)
// Normal operation {
} cerr << "Error: " << msg << endl; //
Handle the exception
}
return 0;
Explanation:
}
• Functionality: The divide function checks if the denominator b is zero. If it is, a string
exception is thrown.
• Flow Control: The try block in main calls divide. If an exception occurs, control moves
to the catch block, which prints the error message.
• Output: The program outputs "Error: Division by zero error" instead of crashing.
Types of Exceptions

Standard Exceptions: C++ provides a hierarchy of standard exception classes in


<stdexcept>, such as:
• std::runtime_error: For errors that can only be detected during runtime.
• std::logic_error: For errors in program logic.
• std::out_of_range: For accessing elements outside of valid ranges.

User-Defined Exceptions: You can create custom exception classes by inheriting


from std::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.

• Re-throwing Exceptions: Use throw; to re-throw the caught exception,


preserving its original context and information.

• Resource Management: Utilize RAII (Resource Acquisition Is Initialization) to


manage resources effectively, preventing leaks.

• Document Exceptions: Clearly document which functions can throw exceptions and
what types they may throw.
15
Exception Safety Levels

• No-throw Guarantee: The operation is guaranteed not to throw


exceptions.

• Strong Guarantee: If an exception occurs, the program state remains


unchanged (rollback).

• Basic Guarantee: If an exception occurs, resources are cleaned up, but


the program's state may change.

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

• Exception handling improves program robustness and user


experience.
• Fundamental components include try, catch, and throw.
• Best practices ensure effective error management and resource
handling.
• Understanding exception safety levels enhances code reliability.

20
Attainment of LOs in alignment to the learning
activities:

LO 1: Implement exception handling


techniques using try, catch, and
throw in C++.

LO 2: Analyze and create


custom exception classes to
manage specific error
conditions.
Galgotias University 21
Post session
activities
Assignment 1: Exception Handling Scenario Design
Task: Create a short program that includes at least two
different exception scenarios.
Requirements:
• Define a function that performs a risky operation
(e.g., division, file access).
• Implement exception handling using try, catch, and
throw.
• Write a brief explanation (100-150 words) of the
errors you chose to handle and why your approach
is effective.

Assignment 2: Analyze an Existing Code Snippet


Task: Review a provided code snippet that lacks exception
handling and identify potential issues.
Requirements:
• List at least three possible errors that could occur in
the code. https://app.wooflash.com/
• Propose how you would implement exception moodle/82AQQP8Q
handling to address these errors.
• Write a short reflection (100-150 words) on how your
Topic of the next lesson

More on Try-catch and


Throw

Galgotias University 23
Review and Reflection from
Students

24

You might also like