Exception types in C++ represent different categories or classes of exceptions that can occur during program execution. Each exception type corresponds to a specific error condition or situation that may arise.
Understanding exception types is crucial for effective error handling. By identifying and categorizing exceptions, programmers can create targeted handling mechanisms to address different types of errors, leading to more robust and reliable software.
#include
#include
int main() {
try {
throw std::runtime_error("Something went wrong!");
} catch (const std::runtime_error& e) {
std::cerr << "Caught a runtime error: " << e.what() << std::endl;
}
return 0;
}
// output //
Caught a runtime error: Something went wrong!
std::runtime_error
class, which is a standard exception class provided by the C++ Standard Library.try
block, we throw an instance of std::runtime_error
initialized with the message "Something went wrong!"
.catch
block catches the exception by reference, allowing us to access information about the exception through the e
variable.e.what()
to the standard error stream.Standard exception types are predefined exception classes provided by the C++ Standard Library. They cover a wide range of common error scenarios, allowing programmers to handle exceptions in a structured and consistent manner.
The standard exception classes are organized in a hierarchical structure, with std::exception
serving as the base class for all standard C++ exceptions. Derived from std::exception
, there are two main categories of standard exception types
Represents errors in the program’s logic or internal errors that can be detected at compile time.
std::invalid_argument
: Thrown when a function argument is invalid.std::domain_error
: Thrown when a mathematical function is called with a domain error.std::length_error
: Thrown when an attempt is made to exceed the maximum length of a container.std::out_of_range
: Thrown when an index is out of the allowed range.Indicates errors detected during runtime that are not related to the program’s logic.
std::range_error
: Thrown when a mathematical operation results in a value outside the range representable by the type.std::overflow_error
: Thrown when an arithmetic overflow occurs during a computation.std::underflow_error
: Thrown when an arithmetic underflow occurs during a computation.std::system_error
: Thrown when a system call fails.Indicates errors detected during runtime that are not related to the program’s logic.
std::range_error
: Thrown when a mathematical operation results in a value outside the range representable by the type.std::overflow_error
: Thrown when an arithmetic overflow occurs during a computation.std::underflow_error
: Thrown when an arithmetic underflow occurs during a computation.std::system_error
: Thrown when a system call fails.
#include
#include
int main() {
try {
throw std::invalid_argument("Invalid argument!");
} catch (const std::invalid_argument& e) {
std::cerr << "Caught an invalid argument error: " << e.what() << std::endl;
}
return 0;
}
// output //
Caught an invalid argument error: Invalid argument!
std::invalid_argument
, a subclass of std::logic_error
, with the message "Invalid argument!"
.catch
block catches the exception by reference, allowing us to access information about the exception through the e
variable.e.what()
to the standard error stream.While C++ provides a variety of standard exception types, there may be situations where none of these types precisely match the error condition you need to represent. In such cases, you can define your own custom exception types to encapsulate specific error scenarios.
std::exception
or one of its subclasses, such as std::runtime_error
or std::logic_error
.what()
method from the base class to provide a custom error message.
#include
#include
class MyException : public std::exception {
public:
MyException(const std::string& message) : msg(message) {}
const char* what() const noexcept override {
return msg.c_str();
}
private:
std::string msg;
};
int main() {
try {
throw MyException("Custom exception occurred!");
} catch (const MyException& e) {
std::cerr << "Caught a custom exception: " << e.what() << std::endl;
}
return 0;
}
// output //
Caught a custom exception: Custom exception occurred!
MyException
that inherits from std::exception
.MyException
class contains a member variable msg
to store the error message.MyException
that initializes msg
with the provided message.what()
method to return the msg
as a C-style string.main()
function, we throw an instance of MyException
with the message "Custom exception occurred!"
.catch
block catches the exception by reference, allowing us to access the error message through the e
variable, and print it to the standard error stream.In complex software systems, it’s common to encounter situations where exception types form hierarchies or categories, allowing for more refined error classification and handling. Advanced exception hierarchies provide a structured approach to organize and categorize exceptions based on their relationships and characteristics.
#include
#include
class FileIOException : public std::runtime_error {
public:
FileIOException(const std::string& message) : std::runtime_error(message) {}
};
int main() {
try {
throw FileIOException("Error while reading file!");
} catch (const FileIOException& e) {
std::cerr << "Caught a file I/O exception: " << e.what() << std::endl;
} catch (const std::exception& e) {
std::cerr << "Caught a generic exception: " << e.what() << std::endl;
}
return 0;
}
// output //
Caught a file I/O exception: Error while reading file!
FileIOException
that inherits from std::runtime_error
, which is a subclass of std::exception
.FileIOException
class has a constructor that takes a message as a parameter and passes it to the constructor of the base class std::runtime_error
.main()
function, we throw an instance of FileIOException
with the message "Error while reading file!"
.catch
block catches the exception of type FileIOException
specifically and prints a custom message.std::exception
, it will be caught by the second catch
block, which prints a generic error message.Exception types in C++ provide a structured approach to error handling, allowing programmers to categorize and handle different types of errors effectively. By understanding basic and advanced exception types, developers can create robust and reliable software that gracefully handles exceptional situations.Happy coding !❤️