When to throw IllegalStateException vs IllegalArgumentException?

假如想象 提交于 2019-12-23 15:12:23

问题


Let's start with the Javadocs:

IllegalStateException

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.

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?

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.

Disclaimer: I understand that I didn't show some code, but I believe this is a specific and pragmatic question to consider for good API design. Let's pretend for a moment that we're back in the good ol' days of stackoverflow, when people were happy to discuss pragmatic questions rather than downvoting anything that doesn't look like homework.


回答1:


Putting in other words:

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

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

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.




回答2:


The other answers highlight when to use IllegalArgumentException or IllegalStateException. But in my view (note: opinion based) these exceptions should not be used in your use case.

To summarize: Some file contains data in a valid format, is successfully loaded into the application but some values are not compliant to your business rules (Note: No IO operations failed, the format is valid => neither IOException nor ParseException should be used, they indicate failed IO operations or invalid formats).

Why you should not use IllegalArgumentException?

This exception is thrown to indicate that a method has been passed an illegal or inappropriate argument. You could argue that you have a method validating the file and the value of a field or the combinations of values of several fields in this file are illegal or non-compliant to your business rules. Yepp, point to you. But if you throw an IllegalArgumentException in this situation you can not separate IllegalArgumentExceptions caused by other libraries (or the standard library or from your own code somewhere else) and the IllegalArgumentExceptions from your validator which indicate a business rule violation easily (sure, you could subclass IAE and catch it in a calling method).

Why do you want to separate these exceptions? Use case: Business rule violations should be presented to the user so he can change his non-compliant inputs. Other IAE's or general any uncatched runtime exception indicates that the request failed on the server for example. In these cases you have to send different responses to clients.


You can argue in a similar way why IllegalStateExceptions should not be used to indicate business rule violations. So, what should be used in your use case? This depends highly on the scale of your application. Some custom subclass of RuntimeException may do the Job for small applications. For larger applications validation libraries like "javax.validation" are worth a try.




回答3:


IllegalStateException is for coding errors, not input errors. It's for when the invariants of a class have been violated, or a method is called when an object is in the wrong state. Examples are using a closed resource, or closing a resource twice.

IllegalArgumentException is when an argument has an invalid value per the method API. Passing -1 when only positive numbers are allowed.

In this case neither exception is appropriate. I would create a sub-class of IOException since there's an error in an input file.




回答4:


I also think that the two methods have a very close semantic.

According to the IllegalArgumentException javadoc, passing an invalid argument may be handled by throwing IllegalArgumentException :

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

But invoking a method with a bad argument may also be handled by throwing IllegalStateException as its javadoc states that :

Signals that a method has been invoked at an illegal or inappropriate time.

Indeed, invoking a method with an inappropriate or illegal argument may also mean that the method was invoked at an illegal or inappropriate time.

To make simple, I think that IllegalArgumentException and IllegalStateException may be used in a interchangeable way by some developers as the issue is caused by the passed argument(s). What I explained above.
While IllegalStateException use cases that are not related to a passed argument have not to be interchanged with IllegalArgumentException.

The nuance being slight, most of libraries mix sometimes their usage.

I am afraid to not be able to give you a more solid explanation. Semantic is semantic and as two things may be interpreted in a closer way, it is often not clearly used.




回答5:


Consider a use case where...

And if those were the only two options I had, in your use-case, I'd lean towards IllegalStateException

Why? Because the argument's are valid, they point to a file, which can be read. It's not the argument that is invalid, it's the fact that parsing the file would invalid the state.

This of course assumes that IllegalStateException and IllegalArgumentException are the only exceptions you are considering.

This is course just MHO. I think the important aspect is, you can define the reasons for using one exception over another in a consistent way which makes your API understandable.

I also agree with Saclyr (+1 to their answer), there are more appropriate exceptions you could use to define why the method call failed (personally, I'd consider java.text.ParserException)



来源:https://stackoverflow.com/questions/48736329/when-to-throw-illegalstateexception-vs-illegalargumentexception

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!