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

exception handling

C++ exception handling involves using try, catch, and throw keywords to manage unexpected events during program execution, such as division by zero. The try block contains code that may raise exceptions, while catch blocks handle those exceptions, allowing for multiple catch statements to address different types of exceptions. C++ also provides standard exceptions that can be utilized in programs to handle common error scenarios.

Uploaded by

suganya.cse
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

exception handling

C++ exception handling involves using try, catch, and throw keywords to manage unexpected events during program execution, such as division by zero. The try block contains code that may raise exceptions, while catch blocks handle those exceptions, allowing for multiple catch statements to address different types of exceptions. C++ also provides standard exceptions that can be utilized in programs to handle common error scenarios.

Uploaded by

suganya.cse
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 9

C++ Exception Handling

An exception is an unexpected event that occurs during program execution. For example,

divide_by_zero = 7 / 0;

The above code causes an exception as it is not possible to divide a number by 0.

The process of handling these types of errors in C++ is known as exception handling.

In C++, we handle exceptions with the help of the try and catch blocks, along with
the throw keyword.

 try - code that may raise an exception

 throw - throws an exception when an error is detected

 catch - code that handles the exception thrown by the throw keyword

An exception is a problem that arises during the execution of a program. A C++ exception is a
response to an exceptional circumstance that arises while a program is running, such as an
attempt to divide by zero.

Exceptions provide a 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.

Assuming a block will raise an exception, a method catches an exception using a


combination of the try and catch keywords. A try/catch block is placed around the code that
might generate an exception. Code within a try/catch block is referred to as protected code,
and the syntax for using try/catch as follows −

try {

// protected code

} catch( ExceptionName e1 ) {

// catch block

} catch( ExceptionName e2 ) {
// catch block

} catch( ExceptionName eN ) {

// catch block

You can list down multiple catch statements to catch different type of exceptions in case
your try block raises more than one exception in different situations.

Throwing Exceptions

Exceptions can be thrown anywhere within a code block using throw statement. The
operand of the throw statement determines a type for the exception and can be any
expression and the type of the result of the expression determines the type of exception
thrown.

Note: The throw statement is not compulsory, especially if we use standard C++ exceptions.

Syntax for Exception Handling in C++

The basic syntax for exception handling in C++ is given below:

try { catch (exception) {

// code that may raise an exception // code to handle exception

throw argument; }

Here, we have placed the code that might generate an exception inside the try block.
Every try block is followed by the catch block.

When an exception occurs, the throw statement throws an exception, which is caught by
the catch block.

The catch block cannot be used without the try block.

Example 1: C++ Exception Handling using namespace std;

// program to divide two numbers int main() {

// throws an exception when the divisor is double numerator, denominator, divide;


0
cout << "Enter numerator: ";
#include <iostream>
cin >> numerator;
cout << "Enter denominator: "; cout << "Error: Cannot divide by " <<
num_exception << endl;
cin >> denominator;
}
try {
return 0;
// throw an exception if denominator
is 0 }

if (denominator == 0) Run Code

throw 0; Output 1

// not executed if denominator is 0 Enter numerator: 72

divide = numerator / denominator; Enter denominator: 0

cout << numerator << " / " << Error: Cannot divide by 0
denominator << " = " << divide << endl;
Output 2
}
Enter numerator: 72
catch (int num_exception) {
Enter denominator: 3

72 / 3 = 24

The above program divides two numbers and displays the result. But an exception occurs if
the denominator is 0.

To handle the exception, we have put the code divide = numerator / denominator; inside the
try block. Now, when an exception occurs, the rest of the code inside the try block is
skipped.

The catch block catches the thrown exception and executes the statements inside it.

If none of the statements in the try block generates an exception, the catch block is skipped.

Notice that we have thrown


the int literal 0 with the code throw 0;.

We can throw any literal or variable or


class, depending on the situation and
depending on what we want to execute
W inside the catch block.
orking of try, throw, and catch statements
The catch parameter int
in C++
num_exception takes the value passed by
the throw statement i.e. the literal 0.

Catching All Types of Exceptions


In exception handling, it is important that we know the types of exceptions that can occur
due to the code in our try statement.

This is so that we can use the appropriate catch parameters. Otherwise,


the try...catch statements might not work properly.

If we do not know the types of exceptions that can occur in our try block, then we can use
the ellipsis symbol ... as our catch parameter.

try {

// code

catch (...) {

// code

C++ Multiple catch Statements

In C++, we can use multiple catch statements for different kinds of exceptions that can result
from a single block of code.

try { catch (exception2) {

// code // code

} }

catch (exception1) { catch (...) {

// code // code

} }

Here, our program catches exception1 if that exception occurs. If not, it will
catch exception2 if it occurs.

If there is an error that is neither exception1 nor exception2, then the code inside of catch
(...) {} is executed.

Notes:

 catch (...) {} should always be the final block in our try...catch statement. This is
because this block catches all possible exceptions and acts as the default catch block.

 It is not compulsory to include the default catch block in our code.


Example 2: C++ Multiple catch Statements

This program divides two numbers and stores the result in an array element. There are two
possible exceptions that can occur in this program:

 If the array is out of bounds i.e. if the index of the array is greater than the size of the
array

 If a number is divided by 0

These exceptions are caught in multiple catch statements.

#include <iostream> // not executed if denominator is 0

using namespace std; arr[index] = numerator /


denominator;
int main() {
cout << arr[index] << endl;
double numerator, denominator, arr[4]
= {0.0, 0.0, 0.0, 0.0}; }

int index; // catch "Array out of bounds"


exception
cout << "Enter array index: ";
catch (const char* msg) {
cin >> index;
cout << msg << endl;
try {
}
// throw exception if array out of
bounds // catch "Divide by 0" exception

if (index >= 4) catch (int num) {

throw "Error: Array out of cout << "Error: Cannot divide by " <<
bounds!"; num << endl;

// not executed if array is out of }


bounds
// catch any other exception
cout << "Enter numerator: ";
catch (...) {
cin >> numerator;
cout << "Unexpected exception!" <<
cout << "Enter denominator: "; endl;

cin >> denominator; }

// throw exception if denominator is 0 return 0;

if (denominator == 0) }

throw 0; Run Code


Output 1 Enter numerator: 5

Enter array index: 5 Enter denominator: 0

Error: Array out of bounds! Error: Cannot divide by 0

Here, the array arr only has 4 elements. Here, the denominator is 0. So we throw
So, index cannot be greater than 3. the int literal 0. This exception is caught by
the second catch block.
In this case, index is 5. So we throw a
string literal "Error: Array out of bounds!". If any other exception occurs, it is caught
This exception is caught by the by the default catch block.
first catch block.
Output 3
Notice the catch parameter const char*
Enter array index: 2
msg. This indicates that
the catch statement takes a string literal as Enter numerator: 5
an argument.
Enter denominator: 2

2.5
Output 2
Here, the program runs without any
Enter array index: 2 problem as no exception occurs.

C++ Standard Exception

C++ has provided us with a number of standard exceptions that we can use in our exception
handling. Some of them are shown in the table below.

Exception Description

std::exception The parent class of all C++ exceptions.

std::bad_alloc Thrown when a dynamic memory allocation fails.

Thrown by C++ when an attempt is made to perform a


std::bad_cast
dynamic_cast to an invalid type.

std::bad_exceptio Typically thrown when an exception is thrown and it cannot be


n rethrown.
C++ Standard Exceptions

C++ provides a list of standard exceptions defined in <exception> which we can use in our
programs. These are arranged in a parent-child class hierarchy shown below −

Here is the small description of each exception mentioned in the above hierarchy −

Sr.N
Exception & Description
o

std::exception
1
An exception and parent class of all the standard C++ exceptions.

std::bad_alloc
2
This can be thrown by new.

3 std::bad_cast
This can be thrown by dynamic_cast.

std::bad_exception
4
This is useful device to handle unexpected exceptions in a C++ program.

std::bad_typeid
5
This can be thrown by typeid.

std::logic_error
6
An exception that theoretically can be detected by reading the code.

std::domain_error
7
This is an exception thrown when a mathematically invalid domain is used.

std::invalid_argument
8
This is thrown due to invalid arguments.

std::length_error
9
This is thrown when a too big std::string is created.

std::out_of_range
10 This can be thrown by the 'at' method, for example a std::vector and
std::bitset<>::operator[]().

std::runtime_error
11
An exception that theoretically cannot be detected by reading the code.

std::overflow_error
12
This is thrown if a mathematical overflow occurs.

std::range_error
13
This is occurred when you try to store a value which is out of range.
std::underflow_error
14
This is thrown if a mathematical underflow occurs.

You might also like