简体   繁体   English

警告级别4中的代码不可达警告

[英]Unreachable code warning in warning Level 4

Can someone explain me why this gives unreachable code warning for *a=9; 有人可以解释一下为什么这会给*a=9;给出无法到达的代码警告吗*a=9; line. 线。 I'm using VS2015 preview and warning level 4 我正在使用VS2015预览和警告级别4

int main(){
int* a = foo();
try{
 *a = 5;
}catch(int)
{
 *a=9;
}
  return 0;
}

This gives unreachable code warning for *a=9 , because your compiler knows that the code in try block will never throw any kind of exception. 这会为*a=9给出无法访问的代码警告,因为您的编译器知道try块中的代码永远不会抛出任何异常。 So your catch block will never execute. 因此,您的catch块将永远不会执行。

Use try/catch when code is prone to throw an exception. 当代码易于引发异常时,请使用try / catch。

The reason it is unreachable is because your code fragment *a = 5 cannot throw an exception. 无法访问它的原因是因为您的代码片段* a = 5无法引发异常。 It might give an access violation (for example if foo returns nullptr), but it will not be handled as a C++ exception. 它可能会导致访问冲突(例如,如果foo返回nullptr),但不会被视为C ++异常。

If that is something you want, you CAN catch access violations using __try/__except, but I think you should only use this under exceptional circumstances. 如果这是您想要的,则可以使用__try / __ except捕获访问冲突,但是我认为您仅应在特殊情况下使用。

https://msdn.microsoft.com/en-us/library/s58ftw19%28v=vs.80%29.aspx?f=255&MSPPError=-2147217396 https://msdn.microsoft.com/zh-cn/library/s58ftw19%28v=vs.80%29.aspx?f=255&MSPPError=-2147217396

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM