7

I am trying to check whether the value passed by an user is valid constant or not. Here is the code I have written.

enum Media_Delivery {
    Streaming, Progressive
}

public class TestMain {
    public static void main(String[] args) {
        String medi_delivery = "streaming";
        try {
            Media_Delivery.valueOf("streaming");
        } catch (IllegalArgumentException e) {
            System.out.print(e);
        }

    }

}

Now, in above code if the String passed is not withing the listed enum then it throws IllegalArgumentException which is obvious.

But my question is: Is this the proper way to validate? As we are using Java's exception mechanism to validate.

Can someone suggest a better idea or what I have coded above itself is the best option ?

-----EDIT--------

Another case which I wanted to discuss:



    public class TestMain {
            public static void main(String[] args) {
                String inputPassed = "2a";
                try {
                    Integer.parseInt(inputPassed);
                } catch (NumberFormatException nfe) {
                    throw new SomeUserDefinedException("Please enter only numeric values");
                }

            }

So is this a good idea ? Or there should be our own parsing mechanism?

1
  • 1
    Usually it is considered bad practice to "code toward exceptions", in other words using exceptions to determine logic. Have a look at what @Chris suggested. Commented Sep 5, 2011 at 5:36

4 Answers 4

9

Exceptions should be used for exceptional conditions; things you don't expect to happen. Validating input isn't very exceptional.

Josh Bloch actually outlines this specifically in his book 'Effective Java' which IMHO is something every Java programmer should have.

EDIT: And this is actually a very good answer to how to approach the problem:

Check valid enum values before using enum

Sign up to request clarification or add additional context in comments.

Comments

2

It is usually best practice not to catch or throw unchecked expressions (IllegalArgumentException is a RuntimeException which counts as "unchecked"). See the Java Tutorials - Exceptions for more details. If you can avoid it, try rewriting your code such that a runtime exception is not needed to be caught. This is a controversial issue, but runtime exceptions exist for a reason: they help the programmer identify bugs. If you catch them, then the bug is not being fixed, it is just being avoided. Try using an if-else statement?

According to the API, "the name must match exactly an identifier used to declare an enum constant." I believe this means the parameter is case-sensitive. In addition, the return type of the valueOf method is some type, not void, so you can't have that statement in the try block. try blocks should contain commands or void methods, such as int x = 3; or System.out.println(3); or something.

--------EDIT-------

OP, in response to your comment:

Like others here have said, it depends on what you're trying to accomplish. I assume that since you have the line Media_Delivery.valueOf("streaming"); in the try block, that you're attempting to see whether "streaming" is equal to one of the enum constants? In that case, you wouldn't need an if-else statement, you could simply write

boolean result = medi_delivery.equals(Media_Delivery.Streaming.name()) || 
  medi_delivery.equals(Media_Delivery.Progressive.name());
System.out.println(result);

Or even better, if you don't want to have multiple || conditions, try a switch statement that cycles through each enum constant, testing the equality of the given string.

-Chris

PS: on naming convention, since enum constants are implicitly static final, it is common practice to declare them in all caps, such as STREAMING and PROGRESSIVE (the Java Tutorials - Enums).

7 Comments

Huh? You can ignore returned objects inside a try catch block just like you can anywhere else in the code. Whether or not its a good idea is a separate topic and one that will depend on what the programmer is trying to accomplish.
So testSubject528491 how do I accomplish the task above with if-else? Can you please put some sample code.
Thanks A Lot Chris for your suggestion and answer.
Doing it that way code maintenance and extension very difficult, as every time the enum is changed code would have to be added or deleted to the if/switch statement. Check out ajaxonomy.com/2007/java/making-the-most-of-java-50-enum-tricks namely the reverse lookup section for a much better way to go about doing this.
This is a nice idea user439407.
|
1

I'd say it depends.

If input comes from GUI element like combobox or anything, where enum values are the only ones to choose - then your approach is ok. Here different value would really be an exception.

But if you're making console app, or textfiled with possibility to type anything then result different then enum values shouldn't be considered as exception. You should use normal if-else or cases with this approach.

generally: use exceptions only for exceptional cases, and not for something that is really likeable to happen.

Comments

1

There is no single "proper" way to validate, what you have would certainly be the way I would validate, but there are other ways(for instance you could put all the valid string values of the enumeration in a HashSet and then check against that set to see if its valid, that is probably what the valueOf method does anyway)

Now if the above approach is any "better" or not, that too is to be pretty subjective. If you are doing the validations in a loop and want to reject anything that contains invalid data, then the exception approach is probably best. If you want to flag all the inappropriate elements then either approach works.... the HashSet will probably be faster if there is a lot of problematic data as you wont have to generate a lot of new exception objects, but even then the difference in performance will be pretty negligible.

1 Comment

performance and use or do not use exception here are two very separate topics ;)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.