When throwing an Exception from a constructor of a class in Java you are leaving yourself open to a security vulnerability.
See here https://www.securecoding.cert.org/confluence/display/java/OBJ11-J.+Be+wary+of+letting+constructors+throw+exceptions
Recently I have started to using https://docs.oracle.com/javase/7/docs/api/java/util/Objects.html#requireNonNull(T,%20java.lang.String
) in methods and constructors to validate for null i.e.
If the argument to the constructor is null then a NullPointerException is thrown from the constructor. So we have arrived in the situation where there is a known security vulnerability.
The article above mentions a strategy for getting around this security flaw (ensuring the Exception is thrown before the constructor of Object is finished executing).
To implement this strategy for every constructor where I want to use requireNonNull I think would be a serious overkill. So I’m wondering what I should do?
1. Don’t ever use requireNonNull to validate for non-null in the constructor
2. Use requireNonNull in the constructor in conjunction with the strategy to avoid the security vulnerability
3. Only use the strategy to avoid the security vulnerability in particular classes (not sure what the criteria would be to determine which classes), and for every other class simply use requireNonNull without this strategy