我发现自己经常编写遵循以下顺序的代码:
是否有适用于此类流程的设计模式?当我尝试将上面的序列包装成一个类时,我经常遇到的直接问题是:
Open()
方法。 答案 0 :(得分:1)
拒绝允许异常处理的组织通常不会处理一组虚假处所。
话虽如此,如果可以证明没有异常可以从有问题的代码块中逃脱,也许可以说服您的组织允许有限的异常使用:
Parse.initialize(new Parse.Configuration.Builder(this)
.applicationId(Const.APP_ID)
.server(Const.SERVER_URL)
.clientKey("")
.build());
预期产出:
#include <iostream>
#include <fstream>
#include <string>
#include <stdexcept>
struct exception_swallower
{
void set_error(std::string msg)
{
success = false;
message = std::move(msg);
}
bool success = true;
std::string message;
};
std::ostream& operator <<(std::ostream& os, const exception_swallower& es)
{
if (es.success) {
return os << "success";
}
else {
return os << "failure: " << es.message;
}
}
// @pre stream shall be initialised with an r-value reference
// to a stream which has already had 'open' called on it.
//
template<class Stream, class Op>
exception_swallower perform_op_on_stream(Stream stream, Op op)
{
// our non-exception return type
exception_swallower ret;
// catch all exceptions
try {
// check that stream did open
if (!stream) {
throw std::runtime_error("stream didn't open");
}
// perform the operations
op(stream);
}
catch(const std::exception& e)
{
// reflect failures in the returned object
ret.set_error(e.what());
}
return ret;
}
// some sample operations
auto null_op = [](auto& ios)
{
// do nothing
};
auto error_op = [](auto& ios)
{
// throw an exception
throw std::runtime_error("error in stream");
};
int main(int argc, char** argv)
{
// note: the stream is created as a temporary, which
// automatically yields an r-value reference.
std::cout << perform_op_on_stream(std::ifstream(argv[0]), null_op) << std::endl;
std::cout << perform_op_on_stream(std::ifstream(argv[0]), error_op) << std::endl;
}