java中最常用的运行时异常有哪些?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1502860/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 13:33:02  来源:igfitidea点击:

What are the most commonly used runtime exceptions in java?

javaexceptionruntime

提问by Winston Chen

As a java programmer who wishes to perfect his programming skills, I often come across the situations that I have to create a runtime exception. I know it's a good practice if one use wisely.

作为一个希望完善自己编程技能的java程序员,我经常会遇到必须创建运行时异常的情况。我知道如果明智地使用它是一种很好的做法。

Personally, NullPointerExceptionand IllegalStateExceptionare the most commonly used in the softwares that I have created. How about you?

就我个人而言,NullPointerExceptionIllegalStateException是我创建的软件中最常用的。你呢?

What runtime exceptions do you often use? In what situations do you use them?

您经常使用哪些运行时异常?你在什么情况下使用它们?

采纳答案by KLE

I never throw NullPointerException. For me, it is one that appears naturally in the code when something goes wrong and that requires a developer to look at what happens. Then (s)he fixes the cause and it doesn't happen again.

我从不抛出NullPointerException。对我来说,当出现问题时,它会自然地出现在代码中,并且需要开发人员查看发生了什么。然后(s)他修复了原因,并且它不会再次发生。

I use IllegalStateExceptionto signal that an object is incorrectly configured or that calls are in an incorrect order. However, we all know that ideally, an object should ensure it can't be in a bad state and that you can't call it in incorrect order (make a builder and a resulting object ...).

我使用IllegalStateException来表示对象配置不正确或调用顺序不正确。然而,我们都知道,理想情况下,一个对象应该确保它不会处于错误状态,并且不能以错误的顺序调用它(创建一个构建器和一个结果对象......)。

I use a lot of IllegalArgumentExceptionwhen a method detects that its parameters are incorrect. This is the responsibility of any public method, to stop processing (to avoid indirect errors that are more difficult to understand). Also, a few ifs in the beginning of a method serve a documentation purpose (documentation that never diverge from the code because it is the code :-) ).

当一个方法检测到它的参数不正确时,我使用了很多IllegalArgumentException。这是任何公共方法的责任,停止处理(以避免更难以理解的间接错误)。此外,if方法开头的几个s 用于文档目的(文档永远不会偏离代码,因为它是代码 :-) )。

     public void myMethod(String message, Long id) {
       if (message == null) {
          throw new IllegalArgumentException("myMethod's message can't be null");
          // The message doesn't log the argument because we know its value, it is null.
       }
       if (id == null) {
          throw new IllegalArgumentException("myMethod's id can't be null");
          // This case is separated from the previous one for two reasons :
          // 1. to output a precise message
          // 2. to document clearly in the code the requirements
       }
       if (message.length()<12) {
          throw new IllegalArgumentException("myMethod's message is too small, was '" + message + "'");
          // here, we need to output the message itself, 
          // because it is a useful debug information.
       }
     }

I also use specific Runtime Exceptionsto signal higher level exceptional conditions.

我还使用特定的运行时异常来表示更高级别的异常情况。

For example, if a module of my application couldn't start, I might have a ModuleNotOperationalExceptionthrown (ideally by a generic code like an interceptor, otherwise by a specific code) when another module calls it. After that architectural decision, each module has to deal with this exception on operations that call other modules...

例如,如果我的应用程序的某个模块无法启动,当另一个模块调用它时,我可能会抛出ModuleNotOperationalException(理想情况下由拦截器之类的通用代码,否则由特定代码)。在做出架构决定之后,每个模块都必须在调用其他模块的操作上处理这个异常......

回答by NawaMan

I use IllegalArgumentExceptionrelatively often. Most of the time, I will try to return the default value as soon as it is logical but some of the time it was not, and so I use this one.

我用的IllegalArgumentException比较频繁。大多数情况下,我会尝试在符合逻辑的情况下尽快返回默认值,但有时并非如此,因此我使用了这个。

Another one I use is ArrayIndexOutOfBoundsException.

我使用的另一个是ArrayIndexOutOfBoundsException.

回答by Andrzej Doyle

I've always considered that runtime exceptions should represent programming errors (e.g. nullreference passed in when not expected, array index out of bounds, etc.) while checked exceptions should represent exceptional conditions in the environment that cannot be "coded away" (e.g. IOException, SQLException).

我一直认为运行时异常应该代表编程错误(例如null,在预期之外传入的引用,数组索引越界等),而检查异常应该代表环境中无法“编码”的异常情况(例如IOExceptionSQLException)。

One violation of this is that sometimes you'll need to wrap what ought to be a checked exception in a RuntimeException, in order to satisfy the definition of an interface. As a brief example, you might have some snazzy implementation of java.util.Listthat manages a distributed list between multiple machines. Clearly this would throw checked exceptions (probably some subclass of IOException) if defined on its own, but the benefits of making this class implement Listis that clients can use it almost transparently, anywhere they use another list.

对此的一种违反是有时您需要将应该是已检查异常的内容包装在 RuntimeException 中,以满足接口的定义。作为一个简短的例子,您可能有一些java.util.List管理多台机器之间的分布式列表的时髦实现。很明显,IOException如果单独定义,这将抛出已检查的异常(可能是 的某个子类),但使此类实现的好处List是客户可以几乎透明地使用它,无论他们使用另一个列表的任何地方。

This can lead to what Joel terms a leaky abstraction, though, so it's important that your documentation is clear what exceptions can be thrown and what they mean! In this case I find a custom subclass of RuntimeExceptionto generally be clearer at communicating the root cause rather than trying to shoehorn it into an existing runtime exception class.

不过,这可能会导致 Joel 所说的“泄漏抽象”,因此,重要的是您的文档要清楚可以抛出哪些异常以及它们的含义!在这种情况下,我发现 的自定义子类RuntimeException通常更清楚地传达根本原因,而不是试图将其硬塞到现有的运行时异常类中。

回答by IAdapter

UnknownException, very usefull :P

UnknownException,非常有用:P

i also like org.apache.commons.lang.NotImplementedException

我也喜欢 org.apache.commons.lang.NotImplementedException

回答by Shruti Rawat

Mostly I don't throw runtime exception. Rather than after checking specific conditions throw user defined exceptions. But the few I have used are - IllegalAccessException , ArithmeticException, NumberFormatException and SecurityException.

大多数情况下我不会抛出运行时异常。而不是在检查特定条件后抛出用户定义的异常。但我使用过的少数是 - IllegalAccessException 、ArithmeticException、NumberFormatException 和 SecurityException。

回答by vinS

According to Joshua Blochin Effective Java,

根据Joshua BlochEffective Java 中的说法,

The most commonly reused exceptions:

最常重用的异常:

  1. IllegalArgumentException
  2. IllegalStateException
  3. NullPointerException
  4. IndexOutOfBoundsException
  5. ConcurrentModificationException
  6. UnsupportedOperationException
  1. 非法参数异常
  2. 非法状态异常
  3. 空指针异常
  4. 索引出界异常
  5. 并发修改异常
  6. 不支持的操作异常