验证方法是否会抛出异常? [英] Should a validate method throw an exception?

查看:139
本文介绍了验证方法是否会抛出异常?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经实现了一个这样使用的一些验证库:

  domain_object.validate()

#以某种方式处理验证错误...
如果domain_object.errors:
在domain_object.errors中的错误:
print(error)

validate()执行检查并填充名为错误



我从其他验证库知道,当验证不成功时,它们会抛出异常。错误消息将作为异常属性传递。



什么方法更好?抛出验证异常是有利的吗?

解决方案

不,我不会认为验证方法应该引发异常。 / p>

这将创建一个反模式,因为调用该方法的客户端代码将合理地期望抛出异常,并且那么需要捕获异常。由于通常建议将异常用于流量控制,所以为什么不返回一个值来指示验证是否成功。客户端代码可以检查返回值并相应地执行。



您基本上完成了与抛出异常相同的事情,但没有额外的成本和差的语义实际上是抛出一个例外。



异常应该保留为真正的特殊条件,而不是正常的程序运行。对我来说,验证失败似乎是一个非常正常的条件,在应用程序的日常操作期间,可以预期。调用代码很容易处理,正常操作会继续。一般而言,情况并非如此。


I've implemented a little validation library which is used like this:

domain_object.validate()

# handle validation errors in some way ...
if domain_object.errors:
    for error in domain_object.errors:
        print(error)

validate() performs the checks and populates a list called errors.

I know from other validation libraries that they throw exception when validation is performed unsuccessfully. Error messages would be passed as an exception property.

What approach is better? Is it advantageous to throw validation exceptions?

解决方案

No, I wouldn't think that a validation method should throw an exception.

That would create a bit of an anti-pattern, as the client code calling the method would reasonably expect an exception to be thrown, and would then need to catch the exception. Since it's generally recommended that exceptions not be used for flow control, why not just return a value indicating whether validation was successful or not. The client code could check the return value and proceed accordingly.

You essentially accomplish the same thing as you would by throwing an exception, but without the extra cost and poor semantics of actually throwing an exception.

Exceptions should be reserved for truly exceptional conditions, not normal operation of a program. Failing validation to me seems like it is a pretty normal condition, something to be expected during the day-to-day operation of an application. It would be easily handled by the calling code, and normal operation would continue. Generally, that's not the case with exceptions.

这篇关于验证方法是否会抛出异常?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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