Preferred way of handling errors when loading an object from a file

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?

2

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.

3

Generally, what is the preferred method for the problem described above, or which method is preferred in which cases?

The prefered method looks like this:

class Object { ... };

std::istream& operator>>(std::istream& in, Object& obj) { /* classic "in" operator*/ }

Client code (1):

Object o;
if(std::cin >> o) {
    // do something with o
}

Client code (2):

Object o;
std::cin.exceptions(std::ios::failbit);
std::cin >> o; // will throw on failure
// do something with o

It is up to your implementation of the input operator, to set the failbit for in (which may or may not throw an exception), in case the values read from the stream are valid for the data types, but not valid for being placed into the Object instance.

This is prefered, because:

  • it is flexible wrt the stream type (with this code, you can just as well use a std::stringstream instance and serialize your data to a string)
  • it doesn’t impose the error handling strategy (client code gets to decide if an exception should be thrown or not)
  • it minimizes knowledge cf. Law of Demeter (the loading function doesn’t need to know what a file – or a file path – is)
  • it integrates and scales properly with the built-in C++ i/o support; that means, you can easily do this:

    Object a;
    int b;
    std::string word;
    
    std::cin >> a >> b >> word; // a is read the same as any int or std::string
    

Downsides:
– unless you are careful on reading, errors may slip by (consider my first example, without the if as an example).

Edit: An extra advantage of writing i/o code with i/o-stream operators, is that you get free integration with other code that uses std::i/o-streams. For example, after you define your operator, you could use boost::lexical_cast with Object instances:

#include <boost/lexical_cast.hpp>

std::ostringstream buffer;
Object a = { /* data here */ };
buffer << a;
auto b = boost::lexical_cast<Object>(buffer.str());

1

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật