• Exception Handling
•Exception handling is the process of detecting and managing runtime errors (called
exceptions) to maintain normal program flow.
• In programming, mistakes that cause unusual conditions (errors) are common. These
errors generally fall into three categories:
• Syntax Errors – Violations of language rules (caught during compilation).
• Logical Errors – Code runs but produces incorrect results due to wrong logic.
• Runtime Errors – Unexpected errors that occur during program execution (e.g., division by zero)
• Exception handling in C++ is a mechanism to detect and manage runtime errors in a
structured way. Examples of runtime errors are.
• Division by zero
• Accessing invalid memory
• File I/O failures
3.
• Exceptions providea way to transfer control from one part of a
program to another. C++ exception handling is built upon three
keywords: try, catch, and throw.
• throw − A program throws an exception when a problem shows up.
This is done using a throw keyword.
• catch − A program catches an exception with an exception handler at
the place in a program where you want to handle the problem.
The catch keyword indicates the catching of an exception.
• try − A try block identifies a block of code for which particular
exceptions will be activated. It's followed by one or more catch blocks.
4.
• try-catch Block
•C++ provides an inbuilt feature for handling exceptions
using try and catch block.
• It is an exception handling mechanism where the code that may cause
an exception is placed inside the try block and the code that handles
the exception is placed inside the catch block.
• Syntax:
try {
// Code that might throw an exception
}
catch (ExceptionType e) {
// exception handling code
}
5.
• Throwing Exceptions
•Throwing exception means returning some kind of value that represent the
exception from the try block. The matching catch block is found using the
type of the thrown value. The throw keyword is used to throw the exception.
• Synatx:
try {
throw val
}
catch (ExceptionType e) {
// exception handling code
}
• There are three types of values that can be thrown as an exception:
• Built-in Types
• Standard Exceptions
• Custom Exceptions
6.
#include <iostream>
using namespacestd;
int main() {
try
{
int age = 15;
if (age >= 18)
{
cout << "Access granted - you are old enough.";
}
else
{
throw (age);
}
}
catch (int myNum) {
cout << "Access denied - You must be at least 18 years old.n";
cout << "Age is: " << myNum;
}
return 0;
7.
• Throwing StandardExceptions
• Standard exceptions are the set of classes that represent
different types of common exceptions.
• All these classes are defined inside <stdexcept> header file
and mainly derived from std::exception class which act as
the base class for Inbuilt exceptions.
8.
For example, thevector at() method throws an out_of_range exception when the
element with given index does not exists.
#include <bits/stdc++.h>
using namespace std;
int main() {
vector<int> v = {1, 2, 3};
try {
// Accessing out of bound element
v.at(10);
}
catch (out_of_range e) {
cout << "Caught: " << e.what();
}
return 0;
9.
• Catching MultipleExceptions
• There can be multiple catch blocks associated with a single try block to
handle multiple types of exceptions.
try {
// Code that might throw an exception
}
catch (type1 e) {
// executed when exception is of type1
}
catch (type2 e) {
// executed when exception is of type2
}
catch (...) {
// executed when no matching catch is found
}
10.
#include <bits/stdc++.h>
using namespacestd;
int main() {
// Code that might throw an exception
try {
int choice;
cout << "Enter 1 for invalid argument, "
<< "2 for out of range: ";
cin >> choice;
if (choice == 1) {
throw invalid_argument("Invalid argument");
}
else if (choice == 2) {
throw out_of_range("Out of range");
}
else {
throw "Unknown error";
}
}
// executed when exception is of type
invalid_argument
catch (invalid_argument e)
{
cout << "Caught exception: " << e.what() << endl;
}
// executed when exception is of type out_of_range
catch (out_of_range e)
{
cout << "Caught exception: " << e.what() << endl;
}
// executed when no matching catch is found
catch (...)
{
cout << "Caught an unknown exception." << endl;
}
return 0;
}
11.
• Catch byValue or Reference
• Catch by Value
o Catching exceptions by value creates a
new copy of the thrown object in the
catch block.
o Generally, the exceptions objects are
not very large so there is not much
overhead of creating copies.
• Catch by Reference
o Catch by reference method just pass
the reference to the exception thrown
instead of creating a copy. Although it
reduces the copy overhead, it is not the
primary advantage of this method.
o The main advantage of this method is
in catching polymorphic exception
types.
12.
• Catch byValue
#include <bits/stdc++.h>
using namespace std;
int main() {
try {
throw runtime_error("This is runtime exception");
}
// Catching by value
catch (runtime_error e) {
cout << "Caught: " << e.what();
}
return 0;
}
13.
• Catch byReference
#include <bits/stdc++.h>
using namespace std;
int main() {
try {
throw runtime_error("This is runtime exception");
}
// Catching by referance
catch (exception& e) {
cout << "Caught: " << e.what();
}
return 0;
}
14.
• Why dowe need Exception Handling in C++?
• Separation of Error Handling Code from Normal Code: There are always if-else
conditions to handle errors in traditional error handling codes. These conditions and
the code to handle errors get mixed up with the normal flow. This makes the code less
readable and maintainable. With try and catch blocks, the code for error handling
becomes separate from the normal flow.
• Functions/Methods can handle only the exceptions They choose: A function can
throw many exceptions but may choose to handle some of them. The other exceptions,
which are thrown but not caught, can be handled by the caller. If the caller chooses
not to catch them, then the exceptions are handled by the caller of the caller.
In C++, a function can specify the exceptions that it throws using the throw keyword.
The caller of this function must handle the exception in some way (either by
specifying it again or catching it).
• Grouping of Error Types: In C++, both basic types and objects can be thrown as
exceptions. We can create a hierarchy of exception objects, group exceptions in
namespaces or classes, and categorize them according to their types.
15.
• Standard Exception
ExceptionDescription
std::exception The parent class of all C++ exceptions.
std::bad_alloc Thrown when a dynamic memory allocation
fails.
std::bad_cast Thrown by C++ when an attempt is made to
perform a dynamic_cast to an invalid type.
std::bad_exception Typically thrown when an exception is
thrown and it cannot be rethrown.
16.
• C++ categorizesexceptions primarily into two broad categories:
Standard Exceptions and User-Defined Exceptions.
1. Standard Exceptions:
These are part of the C++ Standard Library and are defined in
the <exception> header or other relevant headers
like <stdexcept>, <new>, etc. They are designed to handle common
error conditions. Key standard exception classes include:
std::exception:
The base class for all standard C++ exceptions. It provides a
virtual what() method that returns a C-style string describing the
exception.
std::logic_error:
Represents errors that result from faulty program logic and could
theoretically be detected by examining the code. Subclasses include:
17.
•std::domain_error: Mathematical domainerrors (e.g., square root of a negative number).
•std::invalid_argument: Invalid arguments passed to a function.
•std::length_error: Attempting to create an object exceeding its maximum size.
•std::out_of_range: Accessing an element outside the valid range of a container.
std::runtime_error:
Represents errors that occur due to external factors or conditions that cannot be easily predicted by
static code analysis. Subclasses include:
•std::overflow_error: Arithmetic overflow.
•std::underflow_error: Arithmetic underflow.
•std::range_error: Result of a computation is out of range.
•std::ios_base::failure: Input/output failure.
18.
Other specific standardexceptions:
•std::bad_alloc:
• Thrown when a dynamic memory allocation fails (e.g., new operator fails).
•std::bad_cast:
• Thrown by dynamic_cast when a cast to a reference type fails.
•std::bad_typeid:
•Thrown by typeid when an attempt is made to get the type of a null pointer to a polymorphic type.
•std::bad_exception:
•Thrown when an exception is thrown and it cannot be rethrown by the unexpected() handler.
2. User-Defined Exceptions:
Programmers can create custom exception classes by deriving them from std::exception or
another suitable base class. This allows for defining specific error types relevant to the application's
domain, providing more meaningful error handling.
19.
• File I/O
•File Input/Output (I/O) in C++ allows programs to interact with files on a disk,
enabling data persistence and exchange. This is achieved through stream-based
I/O, utilizing class
• File Handling in C++
• In C++, input and output are done in the form of a sequence of bytes called streams. For
example, cin and cout are the objects associated with the standard input and output streams.
These streams are represented by different classes provided in the <iostream> library.
• Similarly, C++ also provides file stream classes to perform input and output operations on
files that are defined inside <fstream> header file.
• File Handling Operations
• There are mainly three main steps in file handling:
• Opening a File
• Read/Write Operations
• Closing a File
20.
• Opening aFile
• Opening a file loads that file in the RAM. In C++, we open a file
by creating a stream to it using the fstream class that
represent the file stream i.e. stream for input and output to the
file.
• Syntax:-
fstream str("filename.ext", mode);
where,
str: Name given to the stream
filename: Name of the file
mode: Represents the way in which we are going to interact with the
file.
21.
• File OpeningModes
Mode Description
ios::in File open for reading. If file does not exists,
ios::out File open for writing: the internal stream buffer supports output operations.
ios::binary Operations are performed in binary mode rather than text.
ios::ate The output position starts at the end of the file.
ios::app
All output operations happen at the end of the file, appending to its existing
contents.
ios::trunc Any contents that existed in the file before it is open are discarded.
22.
• For Example,if we want to open the file for reading, we use the following
opening mode:
fstream filein("file.txt", ios::in);
Similarly, if we want to open the file for writing, we use the following:
fstream fileout("file.txt", ios::out);
These modes can also be combined using OR operator (|). For example,
you can open the file stream in both read and write mode as shown:
fstream str("file.txt", ios::in | ios::out);
If the file opened in write mode does not exists, a new file is created. But
if the file opened in read mode doesn't exists, then no new file is created,
and an exception is thrown
23.
• Write Datato File
• Once the file is opened in the write mode using either fstream or ofstream, we can perform the write operation in similar way
as with cout using << operator.
#include <bits/stdc++.h>
using namespace std;
int main() {
// Open a file
ofstream file(“demo.txt");
// Write the string to the file
file << "Welcome to Object Oriented Programming.";
return 0;
}
24.
• Read Datafrom File
• Once the file is opened in the read mode using either fstream or ifstream, we can perform the write
operation in similar way as with cin using >> operator.
#include <bits/stdc++.h>
using namespace std;
int main() {
// Open a file in read mode
ifstream file(“demo.txt");
string s;
// Read string from the file
file >> s;
cout << "Read String: " << s;
return 0;
}
25.
• Closing theFile
• Closing the file means closing the associated stream and free the resources that we being used. It is
important to close the file after you are done with it, especially in the long running programs to
avoid memory leaks, data loss, etc.
• In C++, the files are closed using the close() member function that is present in all file streams.
#include <bits/stdc++.h>
using namespace std;
int main() {
// Open a file in read mode
ifstream file("GFG.txt");
string s;
// Read string from the file
getline(file, s);
cout << "Read String: " << s;
// Close the file
file.close();
return 0;
26.
• Errors inFile Handling
• Many different types of errors can occur in file handling such as file
not found, disk full, etc. Our programs should expect common
errors and should be able to handle them properly. Following are
some common errors that can occur during file handling:
• File Open Failure
• There can be cases in which the file is not opened due to various
reasons such as it doesn't exists, or the program does not have
permission to open it, etc. In this case, we can use
the is_open() member function of the file stream classes to check
whether the file is opened sucessfullly or not.
27.
#include <bits/stdc++.h>
using namespacestd;
int main() {
fstream file("nonexistent_file.txt", ios::in);
// Check if the file is opened
if (!file.is_open()) {
cerr << "Error: Unable to open file!" << endl;
return 1;
}
file.close();
return 0;
}
28.
• Failure toRead/Write Data
• Another common error is failure to read or write data for reasons such as incorrect mode, etc.
In this case, we can validate operations after each read/write attempt. For example, reading
using getline() can be validated as shows:
#include <bits/stdc++.h>
using namespace std;
int main() {
fstream file("GFG.txt", ios::out);
if (!file.is_open()) {
cerr << "Error: Unable to open file!" << endl;
return 1;
}
string line;
// Checking if getline() read successfully or not
if (!getline(file, line))
cerr << "Error: Failed to read data" << endl;
file.close();