Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What results when you pass an invalid String to a Java enum .valueOf call?

Tags:

java

enums

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?

like image 309
Jay R. Avatar asked May 24 '09 20:05

Jay R.


People also ask

Does enum valueOf throw exception?

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.

What does enum valueOf return?

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.)

Can I pass null in enum Java?

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.

Can enum throw exception?

You can throw unchecked exceptions from an enum constructor.


2 Answers

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).

like image 91
Tom Hawtin - tackline Avatar answered Sep 21 '22 22:09

Tom Hawtin - tackline


I just tried your code. It throws an IllegalArgumentException. Just like the documentation says.

like image 42
Etienne de Martel Avatar answered Sep 21 '22 22:09

Etienne de Martel