exception handling
exception handling
An exception is an unexpected event that occurs during program execution. For example,
divide_by_zero = 7 / 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.
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.
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.
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.
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.
throw 0; Output 1
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.
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
In C++, we can use multiple catch statements for different kinds of exceptions that can result
from a single block of code.
// code // code
} }
// 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.
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
throw "Error: Array out of cout << "Error: Cannot divide by " <<
bounds!"; num << endl;
if (denominator == 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++ 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
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.