Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What exception to throw when an important parameter/dependency is missing?

Take this method

/**  * @return List of group IDs the person belongs to  *  */ public List<String> getGroups() {     if (this.getId().equals("")) return null; } 

I would like to throw exception instead returning null, what's the exception to throw when an important parameter/dependency has not been set?

like image 939
Pentium10 Avatar asked Mar 25 '10 17:03

Pentium10


People also ask

What is a dependency exception?

EXCEPTIONS: The non-custodial parent can claim the exemption if: (A) The custodial parent signs a statement assigning the dependency to the other parent. The non-custodial parent then must attach the statement to his/her tax return. IRS Form 8332 is used for this purpose.

What causes an exception to be thrown?

An exception is thrown for one of three reasons: An abnormal execution condition was synchronously detected by the Java virtual machine. Such conditions arise because: evaluation of an expression violates the normal semantics of the language, such as an integer divide by zero, as summarized in §15.6.

What are the four main possible parts of an exception?

C# exception handling is built upon four keywords: try, catch, finally, and throw. try − A try block identifies a block of code for which particular exceptions is activated.


2 Answers

I'd use IllegalArgumentException if the parameter/argument is controlled from outside, or IllegalStateException if the method is just called at a wrong moment (state). In your specific case I think it's the latter. A (dubious) alternative is NullPointerException.

This should however be explicitly documented in the @throws so that the user understands the reason.

like image 112
BalusC Avatar answered Oct 04 '22 16:10

BalusC


How about IllegalStateException?

like image 32
Stefan Kendall Avatar answered Oct 04 '22 15:10

Stefan Kendall