本文介绍了在Python中提出一个内置异常,但有不同的消息吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可以使用自定义文本提出吗?还可以使用自定义文本生成?

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

文档内容如下:

这意味着只有内置操作应该引发ValueError例外?

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

实际上,我明白创建一个从ValueError或Exception继承的异常类是安全的。但是可以不这样做,直接提出一个ValueError(自定义文本)?

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")?

由于ValueError是内置的,因此引发了ValueError文本)允许用户快速查看涉及的是什么类型的问题,与自定义异常类型(类似于ValueErrorSpecificModule,不是标准)相比。

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

推荐答案

执行以下操作时没有任何操作上的错误:

There's nothing operationally wrong with doing something like:

raise ValueError("invalid input encoding")

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

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.

这篇关于在Python中提出一个内置异常,但有不同的消息吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-20 16:40