What results when you pass an empty String
(or some other unrecognized value, or a null
) to a Java enum .valueOf
call?
For example:
public enum Status { STARTED, PROGRESS, MESSAGE, DONE; }
and then
String empty = ""; switch(Status.valueOf(empty)) { case STARTED: case PROGRESS: case MESSAGE: case DONE: { System.out.println("is valid status"); break; } default: { System.out.println("is not valid"); } }
Basically, I want to know if I'm using a switch statement with the enum, will the default case be called or will I get an exception of some sort?
The valueOf() enum method converts a specified string to an enum constant value. An exception is thrown if the input string doesn't match an enum value.
valueOf. Returns the enum constant of the specified enum type with the specified name. The name must match exactly an identifier used to declare an enum constant in this type. (Extraneous whitespace characters are not permitted.)
If you want to represent null with an enum, then you'll have to explicit this by using a null object pattern manually with a NONE value and a custom implementation for prettyPrint() based on NONE value.
You can throw unchecked exceptions from an enum constructor.
You should get an IllegalArgumentException
if the name is not that of an enum (which it wont be for the empty string). This is generated in the API docs for all enum valueOf
methods. You should get a NullPointerException
for null
. It's probably not a good idea to give a dummy value to your String
variable (nor to allow the last case
/default
to fall through).
I just tried your code. It throws an IllegalArgumentException
. Just like the documentation says.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With