C++ Tutorial

Class and Object

Reference

Inheritance and Derivation

Polymorphism and Virtual Functions

Operator Overloading

Template

Exception

Object Oriented Advanced

Input/Output Stream

File Operations

exception Class: Base Class For Standard Exception in C++

In C++, exception handling provides a systematic way to deal with unexpected situations or errors that may occur during program execution. The standard library provides some exception classes, but you can also create your own custom exception classes to handle specific errors more effectively.

In this tutorial, we'll cover how to create and use custom exception classes in C++.

  • Defining a Custom Exception Class: A custom exception class should be derived from the std::exception class, which is part of the C++ standard library. You can override the what() function to provide a custom error message.

Example:

#include <iostream>
#include <exception>

class CustomException : public std::exception {
public:
    const char* what() const noexcept override {
        return "Custom exception occurred!";
    }
};
  • Throwing and Catching Custom Exceptions: To throw a custom exception, use the throw keyword followed by an object of your custom exception class. Use try and catch blocks to handle the exception.

Example:

#include <iostream>
#include <exception>

class CustomException : public std::exception {
public:
    const char* what() const noexcept override {
        return "Custom exception occurred!";
    }
};

void functionThatThrows() {
    throw CustomException();
}

int main() {
    try {
        functionThatThrows();
    }
    catch (const CustomException& e) {
        std::cout << "Caught exception: " << e.what() << std::endl;
    }
    catch (...) {
        std::cout << "Caught unknown exception." << std::endl;
    }

    return 0;
}

Output:

Caught exception: Custom exception occurred!
  • Adding Custom Data to Exception Class: You can add custom data to your exception class, such as an error code, which provides more information about the error.

Example:

#include <iostream>
#include <exception>
#include <string>

class CustomException : public std::exception {
private:
    int errorCode;
    std::string errorMessage;

public:
    CustomException(int code, const std::string& message) : errorCode(code), errorMessage(message) {}

    int getCode() const {
        return errorCode;
    }

    const char* what() const noexcept override {
        return errorMessage.c_str();
    }
};

void functionThatThrows() {
    throw CustomException(404, "Resource not found");
}

int main() {
    try {
        functionThatThrows();
    }
    catch (const CustomException& e) {
        std::cout << "Caught exception (code: " << e.getCode() << "): " << e.what() << std::endl;
    }
    catch (...) {
        std::cout << "Caught unknown exception." << std::endl;
    }

    return 0;
}

Output:

Caught exception (code: 404): Resource not found

By using custom exception classes in your C++ programs, you can handle errors in a more structured and meaningful way. This can lead to more robust and maintainable code, making it easier to debug and understand error conditions.

  1. Base class for standard exceptions in C++:

    • Description: Introduces the base class for standard exceptions in C++, which is the std::exception class.
    • Example Code:
      #include <iostream>
      #include <exception>
      
      int main() {
          try {
              throw std::exception(); // Throwing an instance of std::exception
          } catch (const std::exception& e) {
              std::cerr << "Caught exception: " << e.what() << std::endl;
          }
          return 0;
      }
      
  2. Derived classes of the exception class in C++:

    • Description: Illustrates the concept of derived classes of std::exception, providing specific exception types for different error scenarios.
    • Example Code:
      #include <iostream>
      #include <stdexcept>
      
      int main() {
          try {
              throw std::runtime_error("Custom runtime error"); // Throwing a derived exception
          } catch (const std::exception& e) {
              std::cerr << "Caught exception: " << e.what() << std::endl;
          }
          return 0;
      }
      
  3. C++ custom exception class example:

    • Description: Demonstrates how to create a custom exception class in C++ by deriving from std::exception.
    • Example Code:
      #include <iostream>
      #include <stdexcept>
      
      class CustomException : public std::exception {
      public:
          const char* what() const noexcept override {
              return "Custom exception: Something went wrong.";
          }
      };
      
      int main() {
          try {
              throw CustomException(); // Throwing a custom exception
          } catch (const std::exception& e) {
              std::cerr << "Caught exception: " << e.what() << std::endl;
          }
          return 0;
      }