C ++ exceptions with message

I'm not sure my custom exception approach is correct. I want to make an exception using special messages, but it seems like I created a memory leak ...

class LoadException: public std::exception { private: const char* message; public: LoadException(const std::string message); virtual const char* what() const throw(); }; LoadException::LoadException(const std::string message) { char* characters = new char[message.size() + 1]; std::copy(message.begin(), message.end(), characters); characters[message.size()] = '\0'; this->message = characters; } 

I use it as follows:

 void array_type_guard(Local<Value> obj, const std::string path) { if (!obj->IsArray()) { throw LoadException(path + " is not an array"); } } try { objects = load_objects(); } catch (std::exception& e) { ThrowException(Exception::TypeError(String::New(e.what()))); return scope.Close(Undefined()); } 

I am afraid that the array created in the constructor is never deleted. But I'm not sure how to remove it - should I add a destructor or maybe use a completely different approach?

Update:

I really tried to use the string class as follows:

 class LoadException: public std::exception { private: const char* msg; public: LoadException(const std::string message); virtual const char* what() const throw(); }; LoadException::LoadException(const std::string message) { msg = message.c_str(); } const char* LoadException::what() const throw() { return msg; } 

But it cannot get an error message, then - when any random output is displayed, when I print "what ()".

+4
source share
3 answers

You can use std:string

 class LoadException: public std::exception { private: std::string message_; public: explicit LoadException(const std::string& message); virtual const char* what() const throw() { return message_.c_str(); } }; LoadException::LoadException(const std::string& message) : message_(message) { } 

Then the C ++ area will take care of cleaning things up for you

+11
source

How about throw std::runtime_error("My very own message");

+12
source

In the constructor I have

 Printer::Printer(boost::asio::io_service& io, unsigned int interval) { if (interval < 1) { throw std::runtime_error("Interval can't be less than one second"); } } 

And when creating the object

 try { Printer p{io, 0}; } catch (std::exception& e) { std::cerr << e.what() << std::endl; } 

the program will exit with a message thrown.

0
source

Source: https://habr.com/ru/post/1489389/


All Articles