C++ Class Level Exceptions
In C++, exceptions can be thrown and caught at the class level. This means that a class can define its own exception types and throw them when errors occur in its methods. Here's an example of how to define and use class level exceptions in C++:
class MyClassException : public std::exception { public: MyClassException(const std::string& msg) : message(msg) {} virtual const char* what() const noexcept { return message.c_str(); } private: std::string message; }; class MyClass { public: void myMethod(int arg) { if (arg < 0) { throw MyClassException("Argument must be non-negative"); } // method code } };
In this example, the MyClassException
class is derived from the std::exception
class, which provides a base class for all standard exceptions. The MyClassException
class defines a constructor that takes a string message as an argument and stores it in a member variable. The what()
method is also overridden to return the stored message.
The MyClass
class has a method called myMethod
that takes an integer argument. If the argument is negative, the method throws a MyClassException
with the message "Argument must be non-negative".
To catch a MyClassException
thrown by a method of the MyClass
class, you can use a try-catch
block like this:
MyClass obj; try { obj.myMethod(-1); } catch (const MyClassException& e) { std::cerr << "Exception caught: " << e.what() << std::endl; }
In this example, the myMethod
method is called with an argument of -1, which causes it to throw a MyClassException
. The try-catch
block catches the exception and prints an error message to the standard error stream.
In summary, class level exceptions provide a way for C++ classes to define their own exception types and throw them when errors occur in their methods. You can catch class level exceptions using try-catch
blocks and handle them appropriately in your code.