if/else 中的流提取

发布于 2024-09-06 10:49:14 字数 699 浏览 4 评论 0原文

假设流提取不会失败,它会

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

眼眸 2024-09-13 10:49:14

是的,逻辑是完全一样的。

而且我永远不会调用 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 ;)

烟织青萝梦 2024-09-13 10:49:14

您的假设是正确的,两个片段的作用相同。

异常是 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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文