Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Exceptions to validate inputs

Tags:

java

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?

like image 694
Chatting_Enabled Avatar asked Sep 05 '11 05:09

Chatting_Enabled


People also ask

What is a validation exception?

A validation exception occurs if an input value does not match the expected data type, range or pattern of the data field. For example, if a user enters an integer value in a data field that expects a DateTime value, a validation exception occurs.

How do you validate inputs?

Validation should aim to be as accommodating as possible of different forms of input for particular data types. For example, telephone numbers are written with different separators and digit groupings. Your form will be easier to use if it can interpret multiple notations. Also, it is helpful to be liberal with input.

What is the difference between exception and validation?

Data validation means checking the data before performing operations that could fail, for example check for 0 before doing a division. Exception handling means well defined behavior if an operation fail, for example if a database query times out.

What are the two types of exceptions that are used to validate the data entry and why do we need both of them?

There are mainly two types of exceptions: checked and unchecked. An error is considered as the unchecked exception.


2 Answers

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

like image 94
Brian Roach Avatar answered Oct 01 '22 06:10

Brian Roach


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

like image 41
chharvey Avatar answered Oct 01 '22 07:10

chharvey