将异常用于非错误目的 [英] using exceptions for non-error purposes

查看:119
本文介绍了将异常用于非错误目的的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用异常来管理不是错误的情况是否是一个好习惯?

Is it a good practice to use exception for managing cases that are not errors ?

像在JavaScript和Python中管理在生成器中的StopIteration大小写(yield keyword)

Like in JavaScript and Python that manage the StopIteration case in generators (yield keyword).

推荐答案

这取决于语言。每种语言都有自己的设计和成语。对于大多数语言,例外应该是例外。

It depends on the language. Each language has it's own design and idioms. For most languages exceptions should be exceptional.

在C ++,Java和C#这样的语言中,使用异常是非常糟糕的形式。

In languages like C++, Java and C# it is very bad form to use exceptions for anything else.

在Python中,异常在迭代结束时更频繁地使用。还有更多的一个模型尝试做你想要的和处理例外,而不是验证输入(更容易询问宽恕而不是许可)。例如,如果要打开文件,在Java中,可以先检查它是否存在,然后打开它,然后检查是否有有效的流。在Python中,您将打开它并使用它。如果失败,你可以处理例外。

In Python, exceptions are used more frequently for things like the end of an iteration. There is much more of a model of try to do what you want and handle the exceptions later rather than validating input ("Easier to Ask Forgiveness than Permission"). For example if you want to open a file, in Java you might check if it exists first and then open it and check to see if you have a valid stream. In Python you would open it and use it. If that fails you handle the exception.

维基百科文章:


Python风格调用在出现错误条件时使用异常。而不是在实际使用文件或资源之前测试访问文件或资源,而是在Python中常规使用它来尝试使用它,如果访问被拒绝则捕获异常。

Python style calls for the use of exceptions whenever an error condition might arise. Rather than testing for access to a file or resource before actually using it, it is conventional in Python to just go ahead and try to use it, catching the exception if access is rejected.

即使不存在错误,异常也可以用作非本地传输控制的更一般的方法。例如,用Python编写的Mailman邮件列表软件使用异常来跳出深层嵌套的消息处理逻辑,当决定拒绝某条消息或保留该消息以供主持人批准时。

Exceptions can also be used as a more general means of non-local transfer of control, even when an error is not at issue. For instance, the Mailman mailing list software, written in Python, uses exceptions to jump out of deeply-nested message-handling logic when a decision has been made to reject a message or hold it for moderator approval.

这篇关于将异常用于非错误目的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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