程序员为什么不显示异常? [英] Why don't programmers show exceptions?

查看:93
本文介绍了程序员为什么不显示异常?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

好的,所以我注意到,正在经历其他人编写的一些程序(用于自我教育)。而且我已经注意到,为什么人们有时没有例外的输出?就像他们会做一个

Okay, so I've noticed, going through some programs other people have written (for education of myself). And I have noticed, why do people sometimes not have an output for their exceptions? Like they'll just do a

public class noException {
  public static void main(String[] args) {
    try {
      System.out.println("Hello World!");
    } catch(Exception e) {

    }
  }
}

您是否要查看已捕获到什么异常?还是归结为程序员的个人偏爱?

Wouldn't you want to see what exception has been caught? Or does it come down to just personal preference with programmers?

推荐答案

是的,这主要是由于两个原因造成的。第一个是通过捕获Exception来捕获任何种类的异常,而您应该单独捕获所有可能的异常,每个异常都在自己的捕获中(尝试一次完全合法)。通过捕获泛型,您可以在代码中放弃另一个意外的异常,从而使调试更加困难。

Yes, this is a bad practice mainly by two reasons. The first one is that by catching Exception you are catching any kind of them, whereas you should catch all possible exceptions individually, each one in its own catch (it is completely legal to do it for one try). By catching the generic you can offuscate another unexpected exceptions in your code and makes it much more difficult to debug.

另一个原因是,一旦捕获到异常,您应该做一些事情,至少要做一些日志,显示错误信息,回滚等等。不想采取任何措施,则应在方括号之间提供注释,以说明通过的原因。

The other reason is that you should do something once you have catched the exception, at least do some log, show an error message, rollback, etc. And if you definitely want to do nothing you should provide a comment between the catch brackets explaining the reason why you pass.

这篇关于程序员为什么不显示异常?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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