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

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

问题描述

我想知道其他 SO 人员在实践中是如何处理和/或防止异常的.

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?

我通常通过基本上说 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天全站免登陆