devxlogo

Generic C++ Exception Handling Class

Generic C++ Exception Handling Class

Question:
I would like to see an example of a generic C++ exception class that could be used across objects.

Answer:
When using exception handling, it is often a good idea to unify all of yourexceptions by inheriting them from a common base class. Here is an example ofhow such a class might be useful.

class MyException {public:	MyException(const std::string &fileName,int line,const std::string &reason)			: fileName_(fileName),line_(line),reason_(reason)			{			}	virtual ~MyException () {}	const std::string &fileName() const { return fileName_;}	int line () const { return line_;}	const std::string &reason() const { return reason;}private:	std::string fileName_, reason_;	int line_;};
Now this can be used as follows:
void foo (){	try 	{		bar () ; // may throw excpetion	}	catch(const MyException& e)	{		cout << e.file() << e.line() << e.reason () << endl;		throw; // propagate the exception	}}
and bar could look like this:
void bar(){	// .,.. some code	throw MyException(__FILE__,__LINE__,”reason for exception”);}
This class may also be specialized for more specific error handling byinheriting from it. The advantage of this: Code that is meant tounderstand the specific exception can do so, but other routines can alwaysuse the base class definition.

Consider this…

class MyMemoryException : public MyException{public:	MyMemoryException(const std::string &fileName,int line,					const std::string &reason,long memoryNeeded):		MyException(fileName,line,reason), memoryNeeded_(memoryNeeded)		{		}	long memoryNeeded() const { return memoryNeeded_; } private:	long memoryNeeded_;};
Now let’s say we have a function called doAlloc that allocates somememory and throws a MyMemoryException when the it runs out of memory. Most routines cannot do anything if they run out of memory, except maybe logthe occurance and bail out. Special handlers in the code may, however,try to do some recovery, and can treat this exception in a special manner. For example:
int main (){	try 	{		startProg ();	}	catch (const MyMemoryException& e)	{		tryToRecover(e.memoryNeeded()); // some action to recover	}	catch (const MyException &e)	{		logException(e);	}	catch (…)	{		cout << "not my exceptions" << endl;	}}
[Note: The handler for the derived class is placed before the base class. This is necessary because the first matching handler is always used. If thebase classes’ handler were first, it would be executed for all exceptionclasses derived from MyException.]

See also  Why ChatGPT Is So Important Today
devxblackblue

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist