If I want to load an object from a file, there are a number of things that can g
ID: 659014 • Letter: I
Question
If I want to load an object from a file, there are a number of things that can go wrong. Thus, one needs a way of handling errors when doing so. In some languages, like haskell, one can return a Maybe object that might contain the newly created object. In C++, although it is in principle possible to create such a convenience class, it is usually not the most straight-forward way to do things. Below I list various ways errors could be handled when loading an object from a file in C++.
Return a pointer:
Object* load_from_file(const char* filename);
By returning a pointer, we can return nullptr in case a problem occured while loading the object.
Take a reference to a default constructed object and return false if a problem occured:
bool load_from_file(const char* filename, Object& obj);
Using this method, a separate initialization method needs to be implemented for the object, which will be called after loading it from the file.
Throw an exception inside the load_from_file function:
Object load_from_file(const char* filename);
Generally, I believe, throwing an exception in such a case might be bad, as this is not really an "exceptional" case.
Load data to an intermediate struct:
struct ObjectData{
//data
};
bool load_from_file(const char* filename, ObjectData& data);
//example use:
ObjectData data;
if(load_from_file("path_to_some_file", data)){
Object(data);
//etc...
}
The difference here with the second method is that you do not need to create an initialization method for Object.
Generally, what is the preferred method for the problem described above, or which method is preferred in which cases?
Explanation / Answer
Don't confuse "exception" with "rare"
The main point of exceptions and exception handling is keeping different types of code apart:
The code that provides the main functionality (the "happy path" code)
Everything else: The code that handles all those 973 other cases where not everything has worked out wonderfully and precisely to your main functionality's liking.
Pulling the code for the not-quite-happy statements out of your happy path code makes the latter nicely simple and understandable. That's what exception handling is about, really (plus keeping the other 973 cases apart from one another as well; plus making sure error handling of errors that occurred during error handling will happen reliably as well).
So your formulation "there are a number of things that can go wrong" is a good indication that an exception is probably the most maintainable-in-the-long-run approach for your case. And that remains true even if the exceptions are more frequent than the happy path case.
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.