Exceptions in C++
In C++, exceptions are a way to handle errors or exceptional situations that occur during program execution. An exception is an object that represents an error or unexpected situation that has occurred in a program, and it is thrown when the error occurs. The exception can then be caught and handled by code that knows how to deal with the error.
Imagine you're following a recipe to bake a cake. The recipe has steps you need to follow to get a delicious cake. But, what if something unexpected happens? For instance, you find out you're out of eggs. This unexpected situation is like an exception in programming.
In programming, an exception is an event that occurs during the execution of a program and disrupts the normal flow of the program's instructions. Just like running out of eggs disrupts your cake-making process.
When an exception occurs, the normal sequence of instructions is interrupted. The program then looks for a way to handle this unexpected situation, which is known as exception handling. In our cake analogy, this would be like having a backup plan, such as using a substitute ingredient for eggs or going to the store to buy more.
The purpose of exceptions and exception handling in programming is to deal with these unforeseen issues smoothly, without crashing the program. It allows the program to handle the problem or report it, and then continue or terminate its execution in a controlled and predictable manner. This makes programs more robust and reliable, just as having a backup plan makes your baking more fail-proof!
//Demo of Exception
//Division by 0
//Author: Kevin Roark
// Including the necessary header file for I/O operations
#include <iostream>
// To use the standard library names without qualifying them with std::
using namespace std;
int main() {
// Wrapping the code inside a try block which might potentially throw an exception
try {
// Declare and initialize the numerator
int numerator = 10;
// Declare and initialize the denominator
int denominator = 0;
// Checking if the denominator equals zero
if (denominator == 0) {
// If the denominator is zero, throw a runtime_error exception
throw runtime_error("Divide by zero error.");
}
// If the denominator is not zero, perform the division operation
cout << "Result is " << numerator / denominator << endl;;
}
// Catch block that handles the exception of type runtime_error
catch (runtime_error& e) {
// If an exception was thrown, print the exception error message
cout << "Exception caught: " << e.what() << endl;
}
// Return zero to signify that the program has executed successfully
return 0;
}
This is a simple program demonstrating how to handle exceptions in C++. In this case, it throws and catches a runtime_error exception when a division by zero is attempted. The try
block contains code that may potentially throw an exception, while the catch
block catches and handles the exception if one is thrown.
When an exception is thrown, the program searches for the nearest catch
block that matches the type of the exception being thrown. If no matching catch
block is found, the program terminates and the exception is not handled.
Exceptions can be useful for handling errors in a program and providing a way to gracefully exit or recover from unexpected situations. However, they should be used sparingly and only for exceptional situations, as they can add overhead to program execution and make the code more complex. Additionally, you should always make sure to properly clean up any resources (such as memory allocations) in the catch
block to avoid memory leaks.
In C++, there are a variety of exceptions that you can throw and catch. An exception is an indication of a problem that occurs during a program's execution. When an exception is thrown, the normal flow of a program is interrupted and the control is transferred to an exception handler.
Here are some common types of exceptions in C++:
Standard Exceptions: These are defined in the
<stdexcept>
header, and they represent common problems that programs encounter. Some examples of standard exceptions include:std::exception
: This is the base class for all standard exceptions. All objects thrown by components of the standard library are derived from this class.std::runtime_error
: This is an exception that theoretically can be detected by reading the code.std::logic_error
: This is a type of error which can be detected before the program is executed, like string length negative, array index out of bounds, etc.std::out_of_range
: This is thrown by member functions of containers when the argument is out of the range.std::invalid_argument
: This is thrown due to invalid arguments.std::bad_cast
: This is thrown by dynamic_cast when it fails to perform a cast.std::bad_alloc
: This is thrown by new when it fails to allocate memory.
User-defined Exceptions: In addition to the standard exceptions provided by C++, programmers can define their own exceptions by inheriting and extending the standard exception classes.
Built-in Data Type Exceptions: You can also throw exceptions of any built-in data type like
int
,char
,float
, etc. However, throwing and catching built-in types is not considered good practice, and it's generally better to use the standard exceptions or user-defined exceptions that inherit from them.Exceptions with No Type (throw;): These are used when you want to re-throw an exception that has been caught to a higher level. The catch block just has the keyword
throw;
with no objects or types following it. This type of exception re-throws the exception currently being handled.
2024 - Programming 3 / Data Structures - Author: Dr. Kevin Roark