Reputation: 95
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?
Upvotes: 7
Views: 19591
Reputation: 76898
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
Upvotes: 9
Reputation: 9326
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).
Upvotes: 2
Reputation: 1756
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.
Upvotes: 1
Reputation: 9283
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.
Upvotes: 1