What Java exception should I use?

Suppose I’m a total lazy ass and I don’t want to put in a few dozen keystrokes necessary for my own class of exceptions (this is not very important what is used, really). However, to pretend that I am following good practices here, I need an existing one that is best suited to my situation.

Problem: I need to throw an exception when the class constructor receives an object in its parameters, which is not found in the specific list that I built elsewhere.

What class of exceptions is suitable for this?

+4
source share
5 answers

IllegalArgumentException

+20
source

IllegalArgumentException is indeed the answer here, but I would say that you have problems with your design. In fact, your class invariant depends on the state of some external object, which is a violation of encapsulation. It is impossible to determine if your constructor call will succeed without knowing any other object, which will lead to a confusing and frivolous API.

This problem is mitigated somewhat if the list you are referencing is a static final non-modifiable list (see java.util.Collections.unmodifiableList() ) and is contained in the class in question, but I still don't really like it. It is best to encapsulate, if possible, valid parameter values ​​in enum , which completely eliminates the need for an exception. I generally don't like the exceptions thrown from the constructors. If you should throw an exception, use the factory method instead.

If an option is not available to you that eliminates the need for an external list, you may need to rethink your design.

+10
source

If you are not afraid of an explosion in the number of classes, you can extend an IllegalArgumentException for this situation.

  public class InvalidInstance extends IllegalArgumentException{ private String[] parameter; public InvalidInstance (String[] param){ this.parameter = param; } public String getMessage() String msg = "YOUR_MESSAGE"; /* I think a string as "The currente object is invalid for parameter "+cycle for over parameter;*/ msg += super.geTMessage(); return msg; } public Constructor(parameter1,...){ String[] param = new String[number_parameters] if... throws new InvalidInstance(param); } 

This way you can write all the parameters that trigger the exception.

This code is not very readable: you can use it if you prefer very structured code. A simple IllegalArgumentException is more common :)

0
source

Just in case, if you have not received this, IllegalArgumentException :)

-2
source

All Articles