C++ - Error Class

Whether you're a newbie or an experienced programmer, any questions, help, or just talk of any language will be welcomed here.

Moderator: Coders of Rage

Post Reply
User avatar
Joeyotrevor
Chaos Rift Cool Newbie
Chaos Rift Cool Newbie
Posts: 62
Joined: Thu Jan 22, 2009 6:24 pm
Programming Language of Choice: C++

C++ - Error Class

Post by Joeyotrevor »

Here's an error class I made for a game I was making, just thought it might to be useful to someone here. It's made for console programs but you can easily change what's in the ExitPrompt() function to make it suit your needs. 8-)

Error.h

Code: Select all

#ifndef ERRORCLASS_H
#define ERRORCLASS_H

#include <string>
#include <iostream>
#include <algorithm>

class Error
{
private:
	static const int RTN_EXITPROMPT = 1;
	static void ExitPrompt();
	static std::string ToLocalFile(std::string filename);
public:
	static void MakeError(std::string message, std::string file, int line);
};

#define MAKE_ERROR(x) Error::MakeError(x, __FILE__, __LINE__)

#endif
Error.cpp

Code: Select all

#include "Error.h"

void Error::ExitPrompt()
{
	std::cout << "Press any key to quit... ";
	//wait for user input
	getchar();
	exit(Error::RTN_EXITPROMPT);
}

std::string Error::ToLocalFile(std::string filename)
{
	//this will hold the new name
	std::string localname;

	//start at the end of the string, loop until a '/' or '\' is found
	for(int i = filename.length()-1; i >= 0; i--)
	{
		if(filename[i] == '/' || filename[i] == '\\')
		{
			//name is finished, but backwards
			//reverse it
			std::reverse(localname.begin(), localname.end());
			return localname;
		}
		//add the character to the local name
		localname += filename[i];
	}

	//found no \ or /
	return filename;
}

void Error::MakeError(std::string message, std::string file, int line)
{
	//display error message
	std::cout << std::endl
		<< "Error occured in file:" << Error::ToLocalFile(file) << " line:" << line <<  " \"" << message << "\"" << std::endl;
	//display exit prompt
	Error::ExitPrompt();
}
To use, simply write

Code: Select all

Error::MakeError("An error occurred!", __FILE__, __LINE__);
or:

Code: Select all

MAKE_ERROR("An error occurred!");

Code: Select all

eb 0c 48 65 6c 6c 6f 20 77 6f 72 6c 64 21 31 d2 8e c2 30 ff b3 0a bd 02 7c b9 0b 00 b8 00 13 cd 10 eb fe
User avatar
MarauderIIC
Respected Programmer
Respected Programmer
Posts: 3406
Joined: Sat Jul 10, 2004 3:05 pm
Location: Maryland, USA

Re: C++ - Error Class

Post by MarauderIIC »

You might also seriously consider a singleton pattern for any kind of logging.
I realized the moment I fell into the fissure that the book would not be destroyed as I had planned.
Post Reply