使用例外来验证输入 [英] Using Exceptions to validate inputs

查看:118
本文介绍了使用例外来验证输入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试检查用户传递的值是否有效。这是我写的代码。

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);
        }

    }

}

现在,在上面的代码中,如果传递的String没有列出枚举的枚举,那么它会抛出 IllegalArgumentException 这是显而易见的。

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

但我的问题是:这是验证的正确方法吗?因为我们正在使用Java的异常机制来验证。

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?

推荐答案

异常情况应该使用例外;你不希望发生的事情。验证输入并不是非常特殊。

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

Josh Bloch实际上在他的Effective Java一书中特别概述了这一点,IMHO是每个Java程序员都应该拥有的。

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

编辑:这实际上是解决问题的一个非常好的答案:

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

在使用枚举前检查有效的枚举值

这篇关于使用例外来验证输入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆