Exception types

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.

Why Understand Exception Types?

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 <iostream>
#include <stdexcept>

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!

				
			

Explanation:

  • In this example, we use the std::runtime_error class, which is a standard exception class provided by the C++ Standard Library.
  • Inside the try block, we throw an instance of std::runtime_error initialized with the message "Something went wrong!".
  • The catch block catches the exception by reference, allowing us to access information about the exception through the e variable.
  • We print the error message returned by e.what() to the standard error stream.

Benefits:

  1. Clarity: Basic exception types provide meaningful names for common error scenarios, making code more readable and understandable.
  2. Consistency: By using standard exception types, you adhere to a common convention, improving the consistency of error handling across different codebases.
  3. Robustness: Standard exception types are designed and tested to handle various exceptional situations reliably, reducing the likelihood of bugs and errors in error-handling code.

Standard Exception Types in C++

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.

Exception Hierarchy:

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

std::logic_error:

Represents errors in the program’s logic or internal errors that can be detected at compile time.

  • Subclasses include:
    • 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.

std::runtime_error:

Indicates errors detected during runtime that are not related to the program’s logic.

  • Subclasses include:
    • 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.

std::runtime_error:

Indicates errors detected during runtime that are not related to the program’s logic.

  • Subclasses include:
    • 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 <iostream>
#include <stdexcept>

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!

				
			

Explanation:

  • In this example, we throw an instance of std::invalid_argument, a subclass of std::logic_error, with the message "Invalid argument!".
  • The catch block catches the exception by reference, allowing us to access information about the exception through the e variable.
  • We print the error message returned by e.what() to the standard error stream.

Benefits:

  1. Clarity: Standard exception types provide meaningful names for common error scenarios, making code more readable and understandable.
  2. Consistency: By using standard exception types, you adhere to a common convention, improving the consistency of error handling across different codebases.
  3. Robustness: Standard exception types are designed and tested to handle various exceptional situations reliably, reducing the likelihood of bugs and errors in error-handling code.

Custom Exception Types in C++

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.

Steps to Define Custom Exception Types:

  1. Inheritance: Custom exception classes typically inherit from std::exception or one of its subclasses, such as std::runtime_error or std::logic_error.
  2. Message Handling: Override the what() method from the base class to provide a custom error message.
  3. Construction: Optionally, define constructors to initialize the exception object with relevant information.
				
					#include <iostream>
#include <stdexcept>

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!

				
			

Explanation:

  • In this example, we define a custom exception class MyException that inherits from std::exception.
  • The MyException class contains a member variable msg to store the error message.
  • We define a constructor for MyException that initializes msg with the provided message.
  • We override the what() method to return the msg as a C-style string.
  • Inside the main() function, we throw an instance of MyException with the message "Custom exception occurred!".
  • The 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.

Benefits:

  1. Specificity: Custom exception types allow you to precisely define and communicate the nature of an error, leading to clearer error messages and more targeted error handling.
  2. Domain-specific Errors: In applications with domain-specific logic, custom exception types can be tailored to represent unique error conditions specific to that domain.
  3. Encapsulation: By encapsulating error details within custom exception types, you promote encapsulation and maintain a separation of concerns between error handling and regular program logic.

Advanced Exception Types and Hierarchies in C++

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 <iostream>
#include <stdexcept>

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!

				
			

Explanation:

  • In this example, we define a custom exception class FileIOException that inherits from std::runtime_error, which is a subclass of std::exception.
  • The 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.
  • Inside the main() function, we throw an instance of FileIOException with the message "Error while reading file!".
  • The first catch block catches the exception of type FileIOException specifically and prints a custom message.
  • If any other exception is thrown that is a subclass of std::exception, it will be caught by the second catch block, which prints a generic error message.

Benefits:

  1. Organized Error Handling: Advanced exception hierarchies allow for organized and structured error handling, making it easier to manage and maintain error-handling code.
  2. Granular Error Reporting: By categorizing exceptions into hierarchies, you can provide more granular error reporting and diagnostics, improving troubleshooting and debugging efforts.
  3. Modular Error Handling: Hierarchical exception types enable modular error handling, where different parts of the codebase can focus on handling specific categories of exceptions, leading to cleaner and more modular code.

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 !❤️

Table of Contents

Contact here

Copyright © 2025 Diginode

Made with ❤️ in India