我正在使用boosts序列化函数来序列化并将数据保存到项目中的外部文件,然后再次读取它们。
我遇到的问题是,如果文件被读入(错误)而不是正确的格式,那么程序会崩溃(可能是预期的)。
如何识别文件格式错误并在程序崩溃前中断读取过程?
编辑:
我在我的read in函数中尝试了一个try catch构造,看起来像这样
int read_binary(file_in_out* object){
std::ifstream ifs((*object).file.c_str());
try
{
boost::archive::binary_iarchive ia(ifs);
ia >> (*object).content;
}
catch (boost::archive::archive_exception& ex)
{
std::cout << "An exception occurred. Exception Nr. " << '\n';
return 1;
}
catch (int e)
{
std::cout << "An exception occurred. Exception Nr. " << e << '\n';
return 1;
}
return 0;
}
当文件与它试图读入的结构无关时,会捕获异常。但是,当我使用过时的版本时,它不会捕获异常并在'ia&gt;&gt;行崩溃(*对象)。内容;”有什么想法吗?
答案 0 :(得分:1)
它不应该崩溃。如果是,请报告库开发人员的错误。
它应该引发异常。因此,您可以尝试捕获存档例外:
http://www.boost.org/doc/libs/1_36_0/libs/serialization/doc/exceptions.html
unregistered_class, // attempt to serialize a pointer of an
// an unregistered class
invalid_signature, // first line of archive does not contain
// expected string
unsupported_version, // archive created with library version subsequent
// to this one
pointer_conflict // an attempt has been made to directly serialize
// an object after having already serialized the same
// object through a pointer. Were this permitted,
// it the archive load would result in the creation
// of extraneous object.
incompatible_native_format, // attempt to read native binary format
// on incompatible platform
array_size_too_short, // array being loaded doesn't fit in array allocated
stream_error // i/o error on stream
invalid_class_name, // class name greater than the maximum permitted.
// most likely a corrupted archive or an attempt
// to insert virus via buffer overrun method.
unregistered_cast // base - derived relationship not registered with
// void_cast_register
另外,抓住std::exception&
例如bad_alloc
,range_error
等。