Module 05 - Marymota/CPP_Modules Wiki



Throwing exceptions is a mechanism to handle errors that my occur at run-time. In the context of this exercise, we will be throwing exceptions to report failures of constructors when or parameters range is not met.

Exception handling is a process of throwing and catching an exception by searching the call chain for a handler from the throw point up through its callers. If a function throws an exception for which there is no matching exception handler the program will be terminated. (This is considered a compiler error and must be avoid).

I'll be applying the library that contains a class that helps applying exceptions. In our header file we create a class for each different exception we need to throw that will inherit from the class std::exception.

class myException : public std::exception {
      const char* what() const throw(); // The function std::what() returns a null character sequence that is used to identify the exception.

Then, we can define the error message that will be sent when this exception is thrown:

const char* ExceptionalClass::myException::what() const throw () {
   return "Descriptive error message";

To throw an exception, we just need to use the _throw _keyword followed by 'myException()' in the cases it may occur:

ExceptionalClass::ExceptionalClass(int age) // Needs to be older than 18
   if (age < 18)
      throw myException();

Now we can prevent an object with age less than 18 to be created using the try and catch keywords when calling the constructor:

try {
   ExceptionalClass human(13)  
} catch (const std::exception e){
   std::cerr << e. what() << std::endl;

// output: Descriptive error message

exception::what() in C++ with Examples

⚠️ ** Fallback** ⚠️