什么时候抛出IllegalStateException和IllegalArgumentException? [英] When to throw IllegalStateException vs IllegalArgumentException?

查看:857
本文介绍了什么时候抛出IllegalStateException和IllegalArgumentException?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

让我们从Javadocs开始:

Let's start with the Javadocs:

IllegalStateException


信号表明某个方法是在非法或不适当的情况下调用的
时间。换句话说,Java环境或Java应用程序不是
处于请求的操作的适当状态。

Signals that a method has been invoked at an illegal or inappropriate time. In other words, the Java environment or Java application is not in an appropriate state for the requested operation.

IllegalArgumentException


抛出该错误表示方法已通过非法或
不适当的参数传递。

Thrown to indicate that a method has been passed an illegal or inappropriate argument.

上述问题是它们非常黑白。考虑一个用例,其中一种方法正在解析调用方提供的文件。该文件存在,可读且格式正确。但是,文件中的某些内容不符合业务规则。在这种情况下,抛出什么适当的异常- IllegalStateException IllegalArgumentException

The problem with the above is that they are very black and white. Consider a use case where a method is parsing a file provided by the caller. The file exists, is readable, and is in the correct format. However, some content in the file is non-compliant with the business rules. What would be an appropriate exception to throw in this case - IllegalStateException or IllegalArgumentException?

查看提供断言的各种库,例如Guava 前提条件或Spring 声明,似乎没有达成共识。在此处,但没有一个能为我上面提到的常见用例提供结论性的答案。

Looking at various libraries that provide assertions, like Guava Preconditions or Spring Assert, it appears that there is no consensus. There are some good discussions here and here, but none provide a conclusive answer to the common use case I stated above.

免责声明:我知道我没有显示一些代码,但是我相信这是一个好的API设计要考虑的具体而实用的问题。让我们假装一下,我们回到了堆栈溢出的美好时光,那时人们乐于讨论务实的问题,而不是拒绝任何看起来不像家庭作业的东西。

推荐答案

换句话说:

在类型被接受但类型为IllegalArgumentException的情况下抛出IllegalArgumentException。

The IllegalArgumentException is thrown in cases where the type is accepted but not the value, like expecting positive numbers and you give negative numbers.

在不应该调用方法时(例如从a调用方法)抛出IllegalStateException。死线程。

The IllegalStateException is thrown when a method is called when it shouldn't, like calling a method from a dead thread.

我不知道它们如何混合。在您关于有问题的文件的问题中,我认为抛出ParseException或IOException会更合适。

I don't see how they could mix. In your question about the file with problems, I think that throwing either a ParseException or an IOException would be more appropriate.

这篇关于什么时候抛出IllegalStateException和IllegalArgumentException?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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