无法访问的代码:错误还是警告? [英] Unreachable code: error or warning?

查看:19
本文介绍了无法访问的代码:错误还是警告?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是一个语言设计问题:

This is a language design question:

您认为无法访问的代码(在一般编程语言中)是否应该引发警告(即报告问题并继续编译")或错误(拒绝编译")?

Do you think unreachable code (in programming languages in general) should raise a warning (i.e. "report problem and compile anyway") or an error ("refuse to compile")?

我个人强烈认为这应该是一个错误:如果程序员编写一段代码,它应该总是打算在 some 场景中实际运行它.但例如 C# 编译器似乎不同意这一点,只报告一个警告.

Personally I strongly feel it should be an error: if the programmer writes a piece of code, it should always be with the intention of actually running it in some scenario. But the C# compiler for example seems to disagree with this and merely reports a warning.

注意:我意识到好的死代码检测是一个非常困难的问题,但这不是这个问题的重点.

Note: I realize good dead code detection is a very difficult problem, but that is not the focus of this question.

以下是一些代码片段的示例,其中某些语句显然无法访问:

Here are some examples of pieces of code where some statements are clearly unreachable:

return;
foo();

--

throw new Exception();
foo();

--

if (...) {
  return;
} else {
  throw new Exception();
}
foo();

推荐答案

一般来说应该是报错.

我想到了一个例外:

if (false) {
  doStuffThatITemporarilyDisabled();
}

如果您的编译器拒绝编译此类代码,一些开发人员可能会抱怨.

Some developers might complain if your compiler denies compilation for code like that.

这篇关于无法访问的代码:错误还是警告?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆