问题描述
让我们从Javadocs开始:
Let's start with the Javadocs:
上述问题是它们非常黑白。考虑一个用例,其中一种方法正在解析调用方提供的文件。该文件存在,可读且格式正确。但是,文件中的某些内容不符合业务规则。在这种情况下,抛出什么适当的异常- 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?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!