防止异常捕获Java中的异常 [英] Preventing exceptions vs. catching exceptions in Java

查看:128
本文介绍了防止异常捕获Java中的异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道其他用户在实践中如何处理和/或防止异常。

I am wondering how in practice other SOers tend to deal with and/or prevent exceptions.

在什么情况下,您可以防止异常,以及如何?
在什么情况下你会捕获异常?

In what situations do you prevent exceptions, and how? In what situations do you catch exceptions?

我通常会阻止'NullPointerExceptions'(和其他类似的),基本上说 if(foo!= null){...}

I usually prevent 'NullPointerExceptions' (and other similar ones) by, well, essentially saying if(foo!=null) {...}

我发现在大多数情况下,这比使用一个try-catch块。

I find that in most situations this is less bulky than everything involved in using a try-catch block.

当潜在的异常更复杂或更多时,我使用try-catch块。

I use try-catch blocks when the potential exceptions are more complex, or more numerous.

推荐答案

在我看来,当引用为null(例如再次)实际上表示一个有效的程序状态时,这是有意义的,以防止NullPointerException(例如) 即可。如果没有,您应该防止它发生,因为在这种情况下,您想要程序死亡。

In my opinion, it only makes sense to prevent a NullPointerException (for example) when a reference being null (again, for example) actually represents a valid program state. If it does not, you should not prevent it from happening, because in that case you want the program to die hard.

在Java中,特定的RuntimeException(例如IllegalArgumentException)下降的某些异常实际上意味着发送编程错误,如果程序正确,则不应该发生这种情况。我试着跟着这个。如果我正在编写一个方法来限制其参数,我不会试图避免抛出异常。我会积极地扔一个。

In Java in particular, certain exceptions descending from RuntimeException (such as IllegalArgumentException) are really meant to signal programming errors, conditions that should not happen if your program is correct. I try to follow this. If I am writing a method that places restrictions on its arguments, I will not try to avoid throwing an exception. I will throw one aggressively.

这篇关于防止异常捕获Java中的异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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