简体   繁体   中英

Own exception in C++ can not be thrown

I'm trying to get a custom exception in C++ working (Linux, g++). Dictionary.hpp :

#ifndef HEADER_DICTIONARY_H
#define HEADER_DICTIONARY_H

#include <map>
#include <string>
#include <stdexcept>

using namespace std;

[...]

class EDictionaryNoLabel : public runtime_error
{
public:
          explicit EDictionaryNoLabel(const string& __arg);
          virtual ~EDictionaryNoLabel() _GLIBCXX_USE_NOEXCEPT;
};

#endif

And in Dictionary.cpp I throw the exception (here is where the compilation fails):

#include <map>
#include <string>
#include "Dictionary.hpp"

using namespace std;

//  map<string, string> dictMap;
Dictionary::Dictionary() {
}

void Dictionary::update(string label, string value) {
        dictMap[label]=value;
}

string Dictionary::read(string label){
        if (0==dictMap.count(label)) {
                throw( EDictionaryNoLabel("label not found") );
        }
        return dictMap[label];
}

void Dictionary::refresh() {
        dictMap.clear();
}

But I can not compile it:

utils/Dictionary.o: In function `Dictionary::read(std::string)':
Dictionary.cpp:(.text+0xbf): undefined reference to `EDictionaryNoLabel::EDictionaryNoLabel(std::string const&)'
Dictionary.cpp:(.text+0xdc): undefined reference to `EDictionaryNoLabel::~EDictionaryNoLabel()'
Dictionary.cpp:(.text+0xe1): undefined reference to `typeinfo for EDictionaryNoLabel'
/tmp/ccXT7dWk.o:(.gcc_except_table+0x68): undefined reference to `typeinfo for EDictionaryNoLabel'
collect2: error: ld returned 1 exit status
make: *** [Test] Error 1

I write my exception exactly as the standard overflow_error (also inheriting from runtime_error ).

A very easy and effective way to derive your own exceptions is:

struct EDictionaryNoLabel : std::runtime_error
{
    using std::runtime_error::runtime_error;
};

That's it.

This gives you all the standard constructors and type-safety. Plus you can add further methods if you need them.

anticipating:

What does using std::runtime_error::runtime_error; do?

copies the names of the base class's constructors into this class's namespace. It gives you all the base class's constructors with no extra code.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM