Swiftorial Logo
Home
Swift Lessons
Tutorials
Learn More
Career
Resources

Standard Exceptions in C++

Introduction

In C++, exceptions are used to handle errors and other exceptional events. Standard exceptions are the predefined exceptions provided by the C++ Standard Library. They form the base class for all standard exceptions and provide a consistent way to handle errors in your programs.

Standard Exception Classes

The standard C++ library provides several exception classes, the most common of which include:

  • std::exception: The base class for all standard exceptions.
  • std::logic_error: Indicates errors in the program logic.
  • std::runtime_error: Indicates errors that occur during program execution.
  • std::bad_alloc: Thrown when memory allocation fails.
  • std::bad_cast: Thrown by a failed dynamic_cast.
  • std::bad_typeid: Thrown by a typeid operator applied to a null pointer.
  • std::out_of_range: Thrown when an invalid array index is used.
  • std::invalid_argument: Thrown when an invalid argument is passed.

Using Standard Exceptions

To use standard exceptions in C++, you need to include the header <stdexcept>. Below is an example of how to use std::out_of_range exception:

#include <iostream>
#include <stdexcept>
#include <vector>

int main() {
    std::vector vec = {1, 2, 3};
    try {
        int value = vec.at(5); // This will throw std::out_of_range
    } catch (const std::out_of_range& e) {
        std::cerr << "Out of range error: " << e.what() << std::endl;
    }
    return 0;
}
                
Output:
Out of range error: vector::_M_range_check: __n (which is 5) >= this->size() (which is 3)

Custom Exceptions

In addition to standard exceptions, you can define your own custom exceptions. Custom exceptions can inherit from the standard exception classes. Here is an example:

#include <iostream>
#include <stdexcept>

class MyException : public std::runtime_error {
public:
    MyException(const std::string& message) : std::runtime_error(message) {}
};

int main() {
    try {
        throw MyException("This is a custom exception");
    } catch (const MyException& e) {
        std::cerr << "Caught custom exception: " << e.what() << std::endl;
    }
    return 0;
}
                
Output:
Caught custom exception: This is a custom exception

Best Practices

When using exceptions in C++, consider the following best practices:

  • Use exceptions to handle errors that are truly exceptional and not part of the normal flow of the program.
  • Ensure that your exception classes are derived from std::exception or its subclasses.
  • Always provide a clear and informative error message with your exceptions.
  • Use try and catch blocks to handle exceptions appropriately.
  • Ensure that resources are properly released in the event of an exception. Consider using RAII (Resource Acquisition Is Initialization) to manage resources.

Conclusion

Standard exceptions in C++ provide a powerful mechanism for error handling. By understanding and utilizing these exceptions, you can write more robust and maintainable code. Remember to follow best practices and ensure that your exception handling strategy is clear and consistent throughout your codebase.