if/else 中的流提取
假设流提取不会失败,它会
if( !(stream >> token) )
throw runtime_error( "Unexpected end of recipe." );
else if( token == "something" )
// do something
else
throw runtime_error( "Unknown token" );
像这样工作吗
if( !(stream >> token) )
throw std::runtime_error( "Unexpected end of recipe." );
if( token == "something" )
// do something
else
throw std::runtime_error( "Unknown token" );
(stream = std::stringstream and token = std::string) 预期结果是 token
包含流中的下一个 ... token... ? 有没有更好的方法来处理错误?就像cerr << “无论如何错误”<<结束; exit();
或者其他什么,或者我的 std::runtime_error
足够好吗?
Assuming the stream extraction won't fail, will this
if( !(stream >> token) )
throw runtime_error( "Unexpected end of recipe." );
else if( token == "something" )
// do something
else
throw runtime_error( "Unknown token" );
Work like this
if( !(stream >> token) )
throw std::runtime_error( "Unexpected end of recipe." );
if( token == "something" )
// do something
else
throw std::runtime_error( "Unknown token" );
(stream = std::stringstream and token = std::string)
And the expected result being token
contains the next ... token... from the stream?
Is there a better way to handle errors? Like cerr << "error whatever" << endl; exit();
or something, or is my std::runtime_error
good enough?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
是的,逻辑是完全一样的。
而且我永远不会调用 exit() - 至少在您的代码中,异常可以被其他代码捕获,而不是仅仅杀死应用程序。您永远不知道将来是否会在更大的应用程序中使用此代码,因此最好保持您的选择开放;)
Yes, the logic is exactly the same.
And I wouldn't ever call exit() - at least in your code the exception can be caught by some other code instead of just killing the app. You never know if you will use this code inside a larger application sometime in the future so it's better to keep your options open ;)
您的假设是正确的,两个片段的作用相同。
异常是 C++ 中处理意外情况的标准方法,因此我不建议使用其他方法来处理错误,除非此错误预计会在常见情况下发生。如果是这种情况,我建议您在函数上使用某种返回值通知。
Your assumptions are correct, the two snippets will act the same.
Exceptions is the standard way of handling unexpected conditions in C++ so I would not recommend to use another way of handling the error, unless this error is expected to happen in common cases. If that is the case, I would suggest some kind of return value notification on you function instead.