Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

你写的 Hello World 大部分都有 bug #2255

Open
jwenjian opened this issue Mar 9, 2022 · 1 comment
Open

你写的 Hello World 大部分都有 bug #2255

jwenjian opened this issue Mar 9, 2022 · 1 comment

Comments

@jwenjian
Copy link

jwenjian commented Mar 9, 2022

一篇分析 Hello World 程序 bug 的文章,指出大部分编程语言的hello world 都有一个 bug。

原文: https://blog.sunfishcode.online/bugs-in-hello-world
简要的介绍和中文翻译: https://www.yuque.com/jwenjian/reading-list/vgur3k

@jwenjian
Copy link
Author

jwenjian commented Mar 18, 2022

有朋友提了一个问题,说这个 bug 怎么解决,刚才研究了一下 JAVA 版本的代码,分享如下:

我研究了一下 Java 的 Hello World, 发现还真有一个 API 可以检测 println() 函数是否遇到了错误,所以正确的 Java 版本的 Hello World 应该是下面这样:

import java.util.*;

public class Test {

  public static void main(String[] args) {
      System.out.println("Hello, World!");
      // 这里检测上面的语句是否遇到了 IOException
      boolean hasError = System.out.checkError();
      System.out.println("hasError = " + hasError);
      if (hasError) {
          // 如果遇到了 IOException,程序应该设置一个非 0 的退出代码
         System.exit(1);
       }
  }
}

最终的执行效果就是:

# 先编译
javac Test.java

# 正常执行
java Test
#Hello, World!
#hasError = false

# 异常执行
java Test > /dev/full
# 这里没有任何输出

# 检查状态码
echo $?
# 1

这么处理是有两个原因:

  1. System.out.println() 函数永远不会抛出 IO 异常
  2. 如果遇到 IO 异常,会在内部设置一个错误状态,此时可以用 checkError() 这个方法来检测。

以上都来自 Java Doc: https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/io/PrintStream.html

对于其他版本的 bug 如何解决,感兴趣的朋友可以试试,欢迎把解决方案分享到这里或者语雀文章的评论区:https://www.yuque.com/jwenjian/reading-list/vgur3k

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

2 participants