Home > Articles > Programming > C/C++

  • Print
  • + Share This
Like this article? We recommend

Like this article? We recommend

Deriving New Exception Classes

The exception classes can be used as is; that is, they can be used simply to report an error message describing the error that has occurred. However, this is virtually useless as an exception handling technique. Simply knowing what the exception was doesn’t do much to increase software reliability. The real value of the exception class hierarchy is the architectural roadmap that the exception classes provide for the designer and the developer. The exception classes provide basic error types that the developer can specialize. Many of the exceptions that occur in a runtime environment can be placed into either the logic_error or runtime_error family of classes. To demonstrate how to specialize an exception class, let’s use the runtime_error class as an example. The runtime_error class is a descendant of the exception class. We can specialize the runtime_error class through inheritance. For instance:

class file_access_exception : public runtime_error{
protected:
 //...
 int ErrorNumber;
 string DetailedExplanation;
 string FileName;
 //...
public:
 virtual int takeCorrectiveAction(void)
 string detailedExplanation(void);
 //...
};

Here, the file_access_exception inherits runtime_error and specializes it by adding a number of data members and member functions. Specifically, the takeCorrectiveAction() method is added. This method can be used to help the exception handler perform its recovery and correction work. This file_access_exception object knows how to identify and break deadlock. It also has specialized logic for dealing with viruses that can damage files or for file transfers that get interrupted unexpectedly. Each of these situations can introduce runtime exceptions. We can use our file_access_exception objects with the throw, catch, and try facilities of C++. For example:

try{
 //...
 fileProcessingOperation();
 //...
}

catch(file_access_exception &E)
{
cerr << E.what() << endl;
 cerr << E.detailedExplanation() << endl;
 E.takeCorrectiveAction();
 // Handler Take Additional Corrective Action
 //...
}

This technique allows you to create ExceptionTable map objects. Using vertical and horizontal polymorphism will also simplify exception handler processing.

  • + Share This
  • 🔖 Save To Your Account