When to throw IllegalStateException and IllegalArgumentException?

Let's start with Javadocs:

IllegalStateException

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

IllegalArgumentException

Thrown to indicate that the method was 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 parses a file provided by a caller. The file exists, is readable, and is in the correct format. However, some materials in the file do not comply with business rules. What would be a suitable exception for this in this case - IllegalStateExceptionor IllegalArgumentException?

Looking at the various libraries that provide assertions like Guava Preconditions or Spring Assert , there seems to be no consensus. There are some good discussions here and here , but none of them provide a convincing answer to the common use case that I have outlined above.

Disclaimer: I understand that I did not show any code, but I believe that this is a specific and pragmatic question that should be considered for a good API design. Let it pretend for a moment that we were back in the good days of the stack overflow, when people were happy to discuss pragmatic issues, and not to devastate everything that does not look like homework.

+4
5

:

IllegalArgumentException , , , , , .

IllegalStateException , , , .

, . , , ParseException, IOException.

+3

, IllegalArgumentException IllegalStateException. , , .

: , , - (: - , = > IOException, ParseException, - ).

IllegalArgumentException?

, , . , , -. Yepp, . IllegalArgumentException , IllegalArgumentException ( ) IllegalArgumentException , - (, IAE ).

? . - , . IAE , , . .


, IllegalStateException -. , ? . RuntimeException . , "javax.validation".

+2

IllegalStateException , . , . .

IllegalArgumentException - API . -1, .

. IOException, .

0

, ...

, , , IllegalStateException

? , , . , , , .

, , , IllegalStateException IllegalArgumentException , .

MHO. , , , API .

Saclyr (+1 ), , , , ( java.text.ParserException)

-1

, .

IllegalArgumentException javadoc IllegalArgumentException:

, , .

, IllegalStateException, javadoc , :

, .

, , .

, , IllegalArgumentException IllegalStateException , . , .
IllegalStateException , , IllegalArgumentException.

, .

. , , , .

-1

Source: https://habr.com/ru/post/1693491/


All Articles