"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > IllegalArgumentException or NullPointerException: Which Exception for a Null Parameter in Setter Methods?

IllegalArgumentException or NullPointerException: Which Exception for a Null Parameter in Setter Methods?

Published on 2024-12-21
Browse:289

IllegalArgumentException or NullPointerException: Which Exception for a Null Parameter in Setter Methods?

When to Throw IllegalArgumentException or NullPointerException for a Null Parameter

When defining setter methods, developers often face the dilemma of whether to throw an IllegalArgumentException or a NullPointerException for a null parameter. Both exceptions appear relevant based on their JavaDoc descriptions:

  • IllegalArgumentException: Indicates an illegal or inappropriate argument.
  • NullPointerException: Thrown when null is used inappropriately.

However, the appropriate choice is IllegalArgumentException (IAE) for the following reasons:

  • Intended Usage: NPE is intended for runtime errors related to null dereferencing, while IAE is designated for validating parameters.
  • Misleading Trace: NPE in a stack trace may suggest a null dereference instead of an incorrect parameter value.
  • Consistency: IAE is commonly used for other invalid parameter errors, so consistency is preferred.
  • Java API Inconsistencies: While the Java API sometimes uses NPE for null parameters, its inconsistency should not be emulated.

Therefore, for setter methods where null is not appropriate, IllegalArgumentException should be used to convey the intent of parameter validation.

Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3