在 Python 中,可以引发内置异常,但使用不同的消息吗?

发布于 2024-08-19 18:21:54 字数 566 浏览 6 评论 0原文

可以使用自定义文本引发内置异常吗?或者也使用自定义文本提出内置警告

文档内容如下:

异常 ValueError:当内置操作或函数接收参数 (...) 时引发

是否暗示只有内置操作应该引发 ValueError 异常?

在实践中,我知道创建一个继承自 ValueError 或 Exception 的异常类是安全的。但不这样做,直接引发 ValueError("custom text") 可以吗?

由于 ValueError 是内置的,与自定义异常类型(例如“ValueErrorSpecificModule”之类的非标准类型)相比,引发 ValueError(使用自定义文本)可以让用户快速查看所涉及的问题类型。

Is it OK to raise a built-in exception with a custom text? or to raise a built-in warning also with custom text?

The documentation reads:

exception ValueError: Raised when a built-in operation or function receives an argument (…)

Is it implied that only built-in operations should raise a ValueError exception?

In practice, I understand that it is safe to create an exception class that inherits from ValueError or Exception. But is it OK not to do that, and directly raise a ValueError("custom text")?

Since ValueError is built-in, raising a ValueError (with a custom text) allows users to quickly see what kind of problem is involved, compared to a custom exception type (something like "ValueErrorSpecificModule", which is not standard).

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

べ映画 2024-08-26 18:21:54

执行以下操作在操作上并没有什么问题:

raise ValueError("invalid input encoding")

事实上,当我编写某些代码的第一遍时,我经常这样做。这样做的主要问题是代码的客户端很难精确地处理异常。为了捕获该特定异常,他们必须对捕获的异常对象进行字符串匹配,这显然是脆弱且乏味的。因此,最好引入您自己的 ValueError 子类;这仍然可以被捕获为 ValueError,但也可以被捕获为更具体的异常类。

一般的经验法则是,每当您有如下代码时:

raise ValueError('some problem: %s' % value)

您可能应该将其替换为以下内容:

class SomeProblem(ValueError):
    """
    Raised to signal a problem with the specified value.
    """
# ...
raise SomeProblem(value)

您可能会说异常类型指定什么出了问题,而消息/属性指定怎么出了问题。

There's nothing operationally wrong with doing something like:

raise ValueError("invalid input encoding")

In fact, I do that quite often when I'm writing the first pass of some code. The main problem with doing it that way is that clients of your code have a hard time being precise in their exception handling; in order to catch that specific exception, they would have to do string matching on the exception object they caught, which is obviously fragile and tedious. Thus, it would be better to introduce a ValueError subclass of your own; this could still be caught as ValueError, but also as the more specific exception class.

A general rule of thumb is that whenever you have code like:

raise ValueError('some problem: %s' % value)

You should probably replace it with something like:

class SomeProblem(ValueError):
    """
    Raised to signal a problem with the specified value.
    """
# ...
raise SomeProblem(value)

You might say that the exception type specifies what went wrong, whereas the message / attributes specify how it went wrong.

錯遇了你 2024-08-26 18:21:54

完全没问题。

但是,您可能希望创建自己的子类来帮助区分内置异常。

例如,如果您有类似 dict 的东西,您可以出于常见原因引发 KeyError,但是如果 KeyError 会怎样?实际上来自您在实现中使用的底层字典。

引发 KeyError 的子类可以更容易地看到实现中存在错误,而不是密钥不在您的对象中

It's perfectly ok.

However you may want to create your own subclass to help distinguish from the builtin exceptions

For example if you have something that works like a dict, you can raise a KeyError for the usual reasons, but what if the KeyError is really coming from an underlying dict you are using in the implementation.

Raising a subclass of KeyError makes it easier to see that there is a bug in the implementation, and not that the key just isn't in your object

蓝海 2024-08-26 18:21:54

没关系,我一直这样做。我发现在许多情况下看到 TypeError 比看到 MySpecialTypeError 更不令人惊讶。

您链接的页面上,我没有看到“内置”一词:

exception TypeError: Raised when an operation or function is applied to an object of inappropriate type. The associated value is a string giving details about the type mismatch.

也许有人看到了您的问题并已经修复了文档。
编辑:看起来您可能已经插入了 ValueError 而不是 TypeError 的文档

It's OK and I do it all the time. I find it less surprising to see TypeError than MySpecialTypeError in many situations.

On the page you linked, I don't see the phrase "built-in":

exception TypeError: Raised when an operation or function is applied to an object of inappropriate type. The associated value is a string giving details about the type mismatch.

Perhaps someone saw your question and fixed the documentation already.
EDIT: It looks like you may have inserted the documentation for ValueError instead of TypeError

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文