I have an Exception class on which I want to set more information before I throw it. Can I create the Exception object, call some of its functions and then throw it without any copies of it being made?
The only method I've found is throwing a pointer to the object:
class Exception : public std::runtime_error
{
public:
Exception(const std::string& msg) : std::runtime_error(msg) {}
void set_line(int line) {line_ = line;}
int get_line() const {return line_;}
private:
int line_ = 0;
};
std::unique_ptr<Exception> e(new Exception("message"));
e->set_line(__LINE__);
throw e;
...
catch (std::unique_ptr<Exception>& e) {...}
But throwing exceptions by pointer is generally avoided, so is there any other way?
There is also the option of setting all the options through the constructor, but this can quickly become unscalable if more fields are added to the class and you want to have fine-grained control over what fields to set:
throw Exception("message"); // or:
throw Exception("message", __LINE__); // or:
throw Exception("message", __FILE__); // or:
throw Exception("message", __LINE__, __FILE__); // etc.