c++ - Error handling when parsing text file to object -
i want parse simple text file , create object data contains. i'm using c++11 (and i'm not fluent).
in case of kind of error (e.g. missing file or invalid text) wish tell caller of parsing function went wrong, providing information kind of error occurred , in file.
i don't consider exceptional errors occur while parsing, seems exceptions not way go.
i thought of returning struct
info, including resulting parsed object in case of success:
struct parsingresult { bool success; int errorcode; int errorline; parsedobject object; }
however i'm not convinced solution because, in case of errors, must still provide parsedobject
. can define default constructor that, of course, it's nature parsedobject
makes sense when parsing successful.
i change parsedobject
parsedobject*
, i'm reluctant use pointers when not necessary, , wonder if can avoided.
my question: can suggest better solution problem? it?
struct obj { // object data... } struct parseerror { int errorcode; int errorline; } class parser { parseerror m_error; // other things public: bool parse(const std::string& filename, obj& parsedobject) { // open file, etc... //parsedobject.property1 = some_value; // if wrong, set m_error , return false; // return true if ok } parseerror getlasterror() { return m_error; } } // in code parser p; obj o; if(!p.parse("filename", o)) { // parseerror = p.getlasterror(); }
Comments
Post a Comment