I'm trying to create a exception handling class for a large-ish project I'm working on which inherits from std::exception. I found this tutorial at cplusplus.com and followed its basic instructions and used its derived class as a template. Here is my Exception class as it stands right now:

#include <exception>
#include "../types.h"

namespace nuclear
{

class Exception : public std::exception
{
public:
	Exception(string_t msg)
	{
		error = msg;
	}
	
	~Exception() throw();
	
	virtual const char* what() const throw()
	{
		return error.c_str();
	}

private:
	string_t error;
};

} // !namespace nuclear

And here is the short test program to try to use it (note the commented-out part):

#include <iostream>
#include "../types.h"
#include "exception.h"

using namespace std;

int main()
{
	nuclear::Exception e("testing...");
	
	/*try
	{
		throw e;
	}
	catch (exception& e)
	{
		cout << e.what() << endl;
	}
	*/
	return 0;
}

No matter what I do, I get this error:

/tmp/ccGK1bXn.o: In function `main':
exception_test.cpp:(.text+0x1d5): undefined reference to `nuclear::Exception::~Exception()'
/tmp/ccGK1bXn.o: In function `nuclear::Exception::Exception(std::basic_string<char, std::char_traits<char>, std::allocator<char> >)':
exception_test.cpp:(.text._ZN7nuclear9ExceptionC1ESs[nuclear::Exception::Exception(std::basic_string<char, std::char_traits<char>, std::allocator<char> >)]+0x1d): undefined reference to `vtable for nuclear::Exception'
collect2: ld returned 1 exit status

What I really want is to be able to define an Exception object as it is thrown, like this:

void dostuff()
{
    // do stuff here... oops, something goes wrong!
    throw nuclear::Exception e("Error: you messed up!");
}

Is that possible? Thank you for your help!

You have to define the destructor. Change line 15 to ~Exception() throw() { } Hope this helps.

Hey, that helped immensely! Thank you!

Granted, I still have other errors to deal with, but at least they're not as cryptic...

Heh heh, after a while you'll begin to understand the messages --even really long hairy ones. Then you start to wonder if you've been staring at this stuff too long... :)

Yeah, it seems obvious now that I know. :)

I still can't get this to work: throw nuclear::Exception e("error"); But this works just fine: nuclear::Exception e("error"); throw e; Not quite as elegant, but it works.

It is because you are using a const-string initializer but your ctor argument is not const. Use the following instead: Exception( const string& msg ) Sorry I didn't catch that earlier.

Actually, as it turns out, this works just fine as my class is now: throw nuclear::Exception("error message"); Apparently, one can throw an object without naming it. I just tested it, and it works. The fellow I'm working with on our largish project pointed this out to me.

Thank you very much again for your help!

This article has been dead for over six months. Start a new discussion instead.