Validating an input string against some enum fields I have this enum below:

public enum TestEnum {
    h1, h2, h3, h4;

    public static String forCode(int code) {
    return (code &gt;= 0 &amp;&amp; code &lt; values().length) ? values()[code].name() : null;
    }

    public static void main(String[] args) {
        System.out.println(TestEnum.h1.name());
        String ss = "h3";

        try {
           TestEnum.valueOf(ss); // but this validates with all the enum values
           System.out.println("valid");
        } catch (IllegalArgumentException e) {
           System.out.println("invalid");
        }           
    }
}


I need to check if the enum value represented by my string ss is one of my enum values h1, h2 or h4. So if h3 is being passed as a string, I would like to return false or throw IllegalArgumentException. I won't need to validate ss with h3 in the enum.

I came up with the below code to do this with the enum, but I believe there is a more elegant solution.

public enum TestEnum {
    h1, h2, h3, h4;

    public static boolean checkExcept(String el, TestEnum... except){
        boolean results = false;
        try{
            results = !Arrays.asList(except).contains(TestEnum.valueOf(el));
        }catch (Exception e){}
        return results;
    }

    public static String forCode(int code) {
        return (code &gt;= 0 &amp;&amp; code &lt; values().length) ? values()[code].name() : null;
    }

    public static void main(String[] args) {

        String ss = "h3";

        if(TestEnum.checkExcept(ss,TestEnum.h1, TestEnum.h2, TestEnum.h3)){
           System.out.println("valid");
        }else{
           System.out.println("invalid");
        }
    }
}


Is there any better way of solving this problem?
I would pass a TestEnum instead of a String to your method, forcing the exception handling to be outside the method. I don't see why you are using Strings at all actually (although I suspect that this is only a small part of your code, and that you have your reasons for needing this).

I would do some refactoring and use EnumSet, which could make your code something like this: (untested code, but I believe it should work)

public static void main(String[] args) {
    String enumName = "h3";
    EnumSet&lt;TestEnum&gt; except = EnumSet.of(TestEnum.h1, TestEnum.h2, TestEnum.h3);

    boolean valid;
    try {
       valid = !except.contains(TestEnum.valueOf(enumName));
    } catch (IllegalArgumentException e) { valid = false; }
    System.out.println(valid ? "valid" : "invalid");
}


Note that I have gotten rid of your entire method here as I think that when you use EnumSet like this, you don't need the method. But of course you can put the relevant parts of the above code into a method.