Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ Exception syntax

I'm having trouble understanding the syntax of exceptions. I have a class template map<T> that has to be able to throw an exception. The code bellow is correct and is used to catch the exception.

try
{       
    map<int> m;
    m["everything"] = 42;
}
catch(map<int>::Uninitialized&)
{
    cout << "Uninitialized map element!" << endl;
}

I was attempting to create a class derived from runtime_error and then throw it from my class. But it seems that my logic is flawed.

class Uninitialized : public runtime_error
{
public:
    Uninitialized() : runtime_error("error") {}
};

T operator[] (const char index[]) const
{
    throw Uninitialized();
    return value;
}
like image 724
user3352790 Avatar asked Apr 11 '26 07:04

user3352790


1 Answers

The basic idea of what you're trying to do is certainly possible, so the exact problem you're encountering isn't entirely clear.

Here's a quick demo that does work, and does roughly what you seem to be trying:

#include <stdexcept>
#include <iostream>

template <class T>
class map { 
public:
    class Uninitialized : public std::runtime_error
    {
    public:
        Uninitialized() : runtime_error("error") {}
    };

    T operator[](const char index[]) const
    {
        throw Uninitialized();
        return T();
    }
};

int main(){ 
    map<int> m;
    try {
        auto foo = m["a"];
    }
    catch (map<int>::Uninitialized &m) {
        std::cerr << "Caught exception:" << m.what()<< "\n";
    }
}
like image 160
Jerry Coffin Avatar answered Apr 13 '26 19:04

Jerry Coffin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!