How to safe implement the use of valueOf in case i get a String different than the supported on the enum ACTION. I mean is possible to force to ACTION.valueOf(valueToCompare) to get a valid value even when happens that valueToCompare is not a valid enum member
I get an expected execution when valueToCompare is "CRY" or "CRYALOT" or "cryalot" etc.
And i get java.lang.IllegalArgumentException on cases like in the code.
public enum ACTION{
CRY,
CRYALOT;
}
public static void main(String[] args) {
String valueTocompare = "posible not expected value".toUpperCase();
switch (ACTION.valueOf(valueToCompare)) {
case CRY:
System.out.println("Cry");
break;
case CRYALOT:
System.out.println("Cry a lot");
break;
default:
System.out.println("catch posible not expected value");
break;
}
}
EDIT & used SOLUTION:
I solved this by using a try-catch as @Peter Lawrey suggested:
public enum ACTION{
CRY,
CRYALOT,
NOTVALID;
}
public static void main(String[] args) {
String valueToCompare = "NOTVALID";
ACTION action;
try {
valueToCompare= "variable posible not expected value".toUpperCase();
action = ACTION.valueOf(valueToCompare);
} catch(IllegalArgumentException e){
System.out.println("Handled glitch on the Matrix");
action = ACTION.NOTVALID;
}
switch (action) {
case CRY:
System.out.println("Cry");
break;
case CRYALOT:
System.out.println("Cry a lot");
break;
default:
System.out.println("catch posible not expected value");
break;
}
System.out.println("We continue normal execution on main thread...");
}