Welcome to our comprehensive guide on C++ Standard Exceptions! In this lesson, we'll delve into the world of error handling in C++ using Standard Exceptions. By the end of this tutorial, you'll be able to understand, use, and create your own exception classes. Let's get started!
Exceptions are exceptional conditions that occur during the execution of a program. Instead of normal program flow, they allow control to jump to another part of the code to handle the error. In C++, exceptions are part of the Standard Template Library (STL).
Standard Exceptions in C++ are predefined classes for common errors. They simplify error handling and promote a cleaner coding style. The most commonly used Standard Exceptions are:
std::runtime_error: Represents runtime errors such as out-of-memory conditions or invalid arguments.std::invalid_argument: Represents errors caused by invalid arguments passed to a function.std::logic_error: Represents errors caused by a faulty logical condition in the program.std::range_error: Represents errors caused by out-of-range conditions, like an index exceeding the bounds of an array.Standard Exceptions form a hierarchy with std::exception as the base class. This hierarchy allows for polymorphic exception handling, making it easier to catch and handle multiple types of exceptions.
std::exception
|
+- std::runtime_error
| |
| +- std::invalid_argument
| |
| +- std::logic_error
| |
| +- std::range_error
|
+- std::exception_ptrTo create an exception, we use the throw keyword followed by an object of an exception class. The part of the code that throws the exception is often called the thrower, while the part that handles the exception is the catcher.
try {
// Code that might throw an exception
} catch (exception_type& ex) {
// Code to handle the exception
}You can create your own exception classes by deriving from std::exception. Custom exceptions make it possible to create domain-specific exceptions and provide more meaningful error messages.
class MyException : public std::exception {
public:
MyException(const char* msg) : std::exception(msg) {}
const char* what() const throw() {
return std::exception::what();
}
};Let's create a simple example where we throw and catch a custom exception:
#include <iostream>
#include <stdexcept>
class InvalidInput : public std::exception {
public:
InvalidInput(const char* msg) : std::exception(msg) {}
const char* what() const throw() {
return std::exception::what();
}
};
int divide(int a, int b) {
if (b == 0) {
throw InvalidInput("Division by zero is not allowed");
}
return a / b;
}
int main() {
try {
int result = divide(10, 0);
std::cout << "Result: " << result << std::endl;
} catch (const InvalidInput& ex) {
std::cerr << "Error: " << ex.what() << std::endl;
}
return 0;
}Which class serves as the base for all Standard Exceptions in C++?
What does the `throw` keyword do in C++?