0% found this document useful (0 votes)
13 views

lect04_unit04_Exception Handling

Uploaded by

fosefan745
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
13 views

lect04_unit04_Exception Handling

Uploaded by

fosefan745
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 5

Paper Code: CIC-211

Subject: Object-Oriented Programming Using C++

Unit04, Lecture 03:

Topics Covered: Exception Handling in C++


1. Introduction to Exception Handling

Exception handling in C++ provides a mechanism to manage runtime errors in a controlled way.
It allows the programmer to separate error-handling code from regular code and enables the
program to deal with unexpected situations (like memory issues, file handling errors, or illegal
operations) in a safe manner.

Basic Concepts:

 Exception: An error or unexpected condition that disrupts the normal flow of execution.
 Throwing an Exception: Using the throw keyword to indicate an error condition.
 Catching an Exception: Using the catch keyword to handle the exception.

2. Exception Handling Mechanism in C++

C++ follows a standard model for exception handling involving three primary constructs:

 try block: Code that might generate an exception is placed inside a try block.
 throw statement: When an error occurs, an exception is "thrown" using the throw keyword.
 catch block: The exception is caught and handled inside a catch block.

Basic Syntax:

try {
// Code that may throw an exception
// If an exception occurs, control is transferred to the catch block
// throw exception;
}
catch (type arg) {
// Code to handle the exception
}

Example-

#include <iostream>

using namespace std;


int main() {
int a = 10, b = 0;
try {
if (b == 0) {
throw "Division by zero error!";
} else {
cout << "Result: " << a / b << endl;
}
}
catch (const char* e) {
cout << "Exception caught: " << e << endl;
}
return 0;
}

Throwing Exceptions:

 Exceptions in C++ are thrown using the throw keyword. The object of any type (primitive
types like int, char, string, or user-defined types) can be thrown as an exception.

 throw 404; // Throwing an integer


 throw "Error occurred"; // Throwing a string
 throw MyException(); // Throwing an object of a custom exception class

Catching Exceptions:

 A catch block can catch exceptions of a specific type. For example, if you throw an
integer, the corresponding catch(int) block will handle it.
 You can have multiple catch blocks to handle different types of exceptions:

try {
// Code that might throw an exception
}
catch (int e) {
// Handle integer exception
}
catch (const char* e) {
// Handle string exception
}
catch (...) {
// Handle any exception
}
Note: The ellipsis (...) in the catch block is called a catch-all handler and it can catch any type of
exception.

Standard Exceptions in C++:

C++ provides a set of standard exceptions that are defined in the <stdexcept> header. Some
commonly used standard exceptions are:

1. std::exception: Base class for all exceptions in C++.


2. std::bad_alloc: Thrown when memory allocation fails (typically used with new).
3. std::out_of_range: Thrown when trying to access an element outside the valid range of a
container.
4. std::invalid_argument: Thrown when an invalid argument is passed to a function.
5. std::runtime_error: Thrown when a runtime error occurs.
6. std::logic_error: Thrown when a logical error is detected in the program.

Example-

#include <iostream>
#include <stdexcept>
using namespace std;

int main() {
try {
throw runtime_error("Runtime error occurred!");
}
catch (runtime_error &e) {
cout << "Caught an exception: " << e.what() << endl;
}
return 0;
}

Output:

Caught an exception: Runtime error occurred!

Custom Exceptions:

You can also define your own exception classes by inheriting from std::exception or any
other standard exception class.

Example:

#include <iostream>
#include <exception>
using namespace std;

class MyException : public exception {


public:
const char* what() const throw() {
return "Custom Exception occurred!";
}
};

int main() {
try {
throw MyException();
}
catch (MyException& e) {
cout << e.what() << endl;
}
return 0;
}

Important Points:

1. Uncaught Exceptions: If an exception is thrown but not caught, the program will
terminate. This is known as an uncaught exception.
2. Exception Propagation: If an exception is not caught in the current function, it
propagates up the call stack, looking for a handler in the calling function.
3. Re-throwing Exceptions: If a catch block wants to pass the exception up to the caller, it
can re-throw the exception using the throw keyword without any arguments.

catch (int e) {
// Handle the exception or re-throw
throw; // Re-throws the caught exception
}

 Nested try-catch Blocks: You can nest try-catch blocks, and exceptions can be thrown and
caught in multiple layers.

 Resource Cleanup (RAII): It's essential to clean up resources like memory, files, and database
connections in case of exceptions. Using RAII (Resource Acquisition Is Initialization) and smart
pointers can help manage this process automatically

Best Practices:
 Throw by value, catch by reference: It is recommended to throw exceptions by value
and catch them by reference to avoid unnecessary copying.
 Use standard exceptions: Prefer using standard exception classes unless you have a
strong reason to define custom exceptions.
 Avoid exception misuse: Exceptions should be used for exceptional situations, not for
normal control flow.

References:-

Online

1. Tutorialspoint OOP Tutorial: Comprehensive tutorials on OOP concepts with examples. Link
2. GeeksforGeeks OOP Concepts: Articles and examples on OOP principles and applications. Link
3. https://canvas.rku.ac.in/courses/3333/pages/specifying-a-class

Book

1. "Object-Oriented Analysis and Design with Applications" by Grady Booch: Classic book covering
fundamental OOP concepts and real-world examples.
2. "Object-Oriented Programming in C++" by Robert Lafore: Detailed guide to OOP in C++, explaining
concepts with a practical example

You might also like