Rethrowing an Exception in C++
Last Updated :
05 Oct, 2023
Exception handling plays a role in developing robust software in C++. It offers a way to handle errors and unexpected situations. One interesting aspect of exception handling in C++ is the ability to rethrow an exception allowing it to pass up the call stack.
Rethrowing an Exception
Rethrowing an exception in C++ involves catching an exception within a try block and instead of dealing with it locally throwing it again to be caught by an outer catch block. By doing this. we preserve the type and details of the exception ensuring that it can be handled at the appropriate level within our program.
This approach becomes particularly valuable when managing exceptions at multiple levels or when additional actions need to be performed before resolving the exception.
To better understand how this works let’s explore an example involving three functions:
Example
C++
#include <iostream>
#include <stdexcept>
using namespace std;
int divide( int numerator, int denominator)
{
try {
if (denominator == 0) {
throw runtime_error( "Division by zero!" );
}
return numerator / denominator;
}
catch ( const exception& e) {
cout << "Caught exception in divide(): " << e.what()
<< endl;
throw ;
}
}
int calculateSum( int a, int b)
{
try {
if (a < 0 || b < 0) {
throw invalid_argument(
"Negative numbers not allowed!" );
}
return a + b;
}
catch ( const exception& e) {
cout << "Caught exception in calculateSum(): "
<< e.what() << endl;
throw ;
}
}
int main()
{
try {
int result = calculateSum(10, divide(20, 2));
cout << "Result: " << result << endl;
int invalidResult = calculateSum(5, divide(10, 0));
cout << "Invalid Result: " << invalidResult << endl;
}
catch ( const exception& e) {
cout << "Caught exception in main: " << e.what()
<< endl;
}
return 0;
}
|
Output
Result: 20
Caught exception in divide(): Division by zero!
Caught exception in main: Division by zero!
Explanation:
- The program first calculates the sum of 10 and the result of dividing 20 by 2, which is 20. This result is printed and there are no exceptions raised in this part.
- Next, the program attempts to divide by zero when calculating the sum of 5 and the result of dividing 10 by 0. This triggers a “Division by zero!” exception which is caught within the divide() function and rethrown. The rethrown exception is then caught in the main() function and is printed as “Division by zero!” along with the appropriate exception handling messages.
The Power of Rethrowing Exceptions
Rethrowing exceptions in C++ has the following advantages advantages:
1. Exception Type Preservation
The preservation of exception handling in C++ is a feature. It enables catch blocks at levels to effectively handle specific types of exceptions allowing for more precise error management.
2. Additional Processing
Additionally rethrowing exceptions provides the opportunity to perform operations or log extra information about the exception before it is caught again further up the call stack. For example you can add debugging details offer context or encapsulate the original exception within another exception to provide more helpful information to higher level catch blocks.
C++
try {
}
catch ( const exception& e) {
throw runtime_error( "Additional information: "
+ string(e.what()));
}
|
3. Catching Exceptions by Reference
When rethrowing an exception it is crucial to catch it by reference (const std;;exception&) rather than by value. This ensures that the exception object remains valid after being caught and rethrown multiple times during the exception handling process.
4. Handling Nested Exceptions
C++ also allows for nested exceptions where one exception is raised inside the catch block of another exception. If a nested exception is rethrown it becomes part of the exception as a std;;nested_exception. This feature enables handling of outer and nested exceptions if necessary.
C++
try {
try {
throw runtime_error( "Nested exception" );
}
catch ( const exception& nested) {
throw_with_nested(logic_error( "Outer exception" ));
}
}
catch ( const exception& outer) {
try {
rethrow_if_nested(outer);
}
catch ( const exception& nested) {
}
}
|
5. Exception Propagation
Rethrowing exceptions allows them to propagate up the call stack until they are eventually caught and handled by a catch block. Any function in the call stack can halt the propagation of an exception by catching it and rethrowing it. This mechanism ensures that exceptions are handled based on the context in which they arise. In C++ rethrowing exceptions is an approach to effectively manage and handle them.
You can use exception handling in an controlled way to manage exceptions in your C++ programs. It gives you the ability to control how exceptions are handled preserve the types of exceptions perform processing and effectively handle nested exceptions. By understanding and utilizing the idea of exceptions you can write C++ programs that are more resilient and dependable.
Related Articles:
Similar Reads
Catch and Throw Exception In Ruby
An exception is an object of class Exception or a child of that class. Exceptions occurs when the program reaches a state in its execution that's not defined. Now the program does not know what to do so it raises an exception. This can be done automatically by Ruby or manually. Catch and Throw is si
3 min read
Python Print Exception
In Python, exceptions are errors that occur at runtime and can crash your program if not handled. While catching exceptions is important, printing them helps us understand what went wrong and where. In this article, we'll focus on different ways to print exceptions. Using as keywordas keyword lets u
3 min read
Exception Handling in C++
In C++, exceptions are unexpected problems or errors that occur while a program is running. For example, in a program that divides two numbers, dividing a number by 0 is an exception as it may lead to undefined errors. The process of dealing with exceptions is known as exception handling. It allows
11 min read
Polymorphic Exceptions In C++
C++ is a powerful programming language that allows developers to handle errors and exceptional situations using exceptions. In this article, we will explore the concept of polymorphic exceptions in C++. Polymorphic exceptions allow you to create custom exception classes that can be caught at differe
3 min read
How to Throw a Custom Exception in Kotlin?
In addition to the built-in Exception Classes, you can create your own type of Exception that reflects your own cause of the exception. And you will appreciate the use of Custom Exception when you have multiple catch blocks for your try expression and can differentiate the custom exception from regu
2 min read
Throwing an Exception vs Mono.error() in Spring WebFlux
In Spring Webflux, reactive programming is embraced, introducing concepts like Mono and Flux for asynchronous data handling. In this article, we will learn the differences between throwing exceptions and using Mono.error() in Spring Webflux. Exceptions and Error Handling in Spring WebfluxExceptions:
3 min read
Raising Exceptions in Ruby
An exception is an unwanted or unexpected event, which occurs during the execution of a program i.e at runtime, that disrupts the normal flow of the programâs instructions. As we know, the code enclosed between begin and end block is totally secured for handling Exceptions and the rescue block tells
4 min read
Define Custom Exceptions in Python
In Python, exceptions occur during the execution of a program that disrupts the normal flow of the programâs instructions. When an error occurs, Python raises an exception, which can be caught and handled using try and except blocks. Hereâs a simple example of handling a built-in exception: [GFGTABS
3 min read
How to Ignore an Exception and Proceed in Python
There are a lot of times when in order to prototype fast, we need to ignore a few exceptions to get to the final result and then fix them later. In this article, we will see how we can ignore an exception in Python and proceed. Demonstrate Exception in Python Before seeing the method to solve it, l
3 min read
Define Exception handling in ES6
Exception: Exceptions are unwanted event that basically interrupts the normal flow of program. There are two types of exception in general:- Synchronous (eg. runtime errors)Asynchronous (eg. system errors) Exception Handling: Often a times exception happens in a program that causes the program to te
3 min read