Handling Exceptions

An important part of the book Learning C++  exception handling, and especially exception handling in C++ 20. Here is an example:



#include <strexcept>
#include <iostream>



class MyException : public std::runtime_error
{
public:
MyException(const char* message) : std::runtime_error(message) {}



/* a constructor for MyException that takes a message argument and passes it to the base class
constructor */
};



class MyClass
{
public:
   void foo()
   {
      throw MyException("An error occurred in MyClass::foo()");
      /* throw an instance of MyException with a custom message */
   }
};



int main()
{
   MyClass obj;
   try
   {
      obj.foo(); // call MyClass::foo() inside a try block
   }
   catch (const std::exception& e)
   {
      std::cerr << "Exception caught: " << e.what() << std::endl;
      /* catch any exception of type std::exception or its derived classes and print its error message to the
         standard error stream */
   }
   return 0;
}




Unknown's avatar

About רות האפרתי Ruth Haephrati

Founder of Secured Globe, Inc. Angel investor and Entrepreneur. https://www.securedglobe.com. Author of the book https://manning.com/books/learning-c-plus-plus
This entry was posted in Code Snippets. Bookmark the permalink.

Leave a comment