c++ - if (condition) try {...} 在 C++ 中合法吗?

标签 c++ exception try-catch language-lawyer

例如:

if (true) try
{
    // works as expected with both true and false, but is it legal?
}
catch (...)
{
    // ...
}

换句话说,将try-block 放在if条件之后是否合法

最佳答案

try block (在 C++ 中是 statement)的语法是

try compound-statement handler-sequence

if的语法是:

attr(optional) if ( condition ) statement_true      
attr(optional) if ( condition ) statement_true else statement_false     

地点:

statement-true - any statement (often a compound statement), which is executed if condition evaluates to true
statement-false - any statement (often a compound statement), which is executed if condition evaluates to false

所以是的,您的代码是 C++ 中的合法代码。

statement_true 在你的情况下是一个 try block 。

在合法性上,类似于:

if (condition) for(...) {
    ...
}

但是您的代码可读性不强,并且在添加 else 时可能成为某些 C++ 陷阱的受害者。因此,在您的情况下,建议在 if 之后添加显式 {...}

关于c++ - if (condition) try {...} 在 C++ 中合法吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35985592/

相关文章:

vb.net - linq 查询导致 System.AccessViolationException

exception - Word Automation InvalidCastException RPC/COM 异常

exception - 向Groovy中的Exception或Error添加更多上下文

c++ - int 和 char 数组有什么区别?

c++ - set_difference并不总是返回正确的答案

c++ - 需要关于 boost::mpl 的解释

java - 如果使用 try{}catch{} 捕获错误,代码是否会继续执行

c++ - 创建一个 alpha 蒙版(glBlendFunc 现在做什么?)

swift - 在 Swift 中转发错误

php - 区分 PHP 错误和应用程序错误