简体   繁体   English

为什么要传递一个字符串参数来引发 Exception()

[英]Why pass a string argument to raise Exception()

I'm working through a chapter on exceptions in Python and the author gives the following example, some different exceptions are stored in a list, one or none is chosen randomly and handled:我正在阅读 Python 中有关异常的一章,作者给出了以下示例,一些不同的异常存储在一个列表中,随机选择一个或没有一个并处理:

import random
some_exceptions = [ValueError, TypeError, IndexError, None]

try:
    choice = random.choice(some_exceptions)
    print(f'raising {choice}')
    if choice:
        raise choice('An Error') # Don't understand the need for the 'An Error' argument
except ValueError:
    print('Caught a ValueError')
except TypeError:
    print('Caught a TypeError')
except Exception as e:
    print(f'Caught some other error: {e.__class__.__name__}')
else:
    print('This code is called if there is no exception')
finally:
    print('This code is always called')

I don't understand the line raise choice('An Error') , the words 'An Error' are never output to the console and the example appears to work just as well with that line changed to raise choice() , is there any specific reason the author did this?我不明白raise choice('An Error')行,'An Error' 一词从来都不是 output 到控制台,并且该示例似乎与该行更改为raise choice()一样好用,有没有作者这样做的具体原因是什么?

Exceptions are classes too.例外也是类。 the string are parameter passed to the class.该字符串是传递给 class 的参数。

In [10]: help(ValueError)

In [11]: v = ValueError("value is not accepted.")

In [12]: v
Out[12]: ValueError('value is not accepted.')

In [13]: v.args
Out[13]: ('value is not accepted.',)

When you use Try catch in python in this way:当您以这种方式在 python 中使用 Try catch 时:

choice = ValueError
try:
    raise choice('An Error')
except ValueError as e:
    print(e)

You will get "An Error" printed it is useful to customize output error so you can know where the error happened like so:您将打印“错误”,自定义 output 错误很有用,这样您就可以知道错误发生的位置,如下所示:

choice = ValueError
a = int(input("Enter a number a"))
b = int(input("Enter a number b"))
try:
    error = "No error"
    if a == 0:
        error = "a is Null"
    if b == 0:
        error = "b is Null"
    raise choise(error)
except ValueError as e:
    print(e)

In this code you can track From where the error comes from if you do for example a division by a or b and you get a Null division error在此代码中,您可以跟踪错误的来源,例如除以 a 或 b 并得到 Null 除法错误

Exceptions are classes.例外是类。 If you write your own (deriving eg from ValueError) the constructor of instance creation - this is what do by writing ValueError() - may store this string to be output by the __str__ method of the exception.如果您编写自己的(例如从 ValueError 派生)实例创建的构造函数 - 这是通过编写ValueError()所做的 - 可以通过异常的__str__方法将此字符串存储为 output。 So if the exception type is insufficient for pinpointing the reason the string argument may prove useful.因此,如果异常类型不足以确定字符串参数可能有用的原因。

I think you are confused how the raise command works.我认为您对 raise 命令的工作方式感到困惑。 It takes a class which already has some inbuilt some stuff like an Exception class.它需要一个 class,它已经有一些内置的东西,比如异常 class。 It cannot raise exception on any class.它不能在任何 class 上引发异常。 If you need to raise that message, go about like如果您需要提出该消息,go 大约像

import random
some_exceptions = [ValueError, TypeError, IndexError, None]

try:
    choice = random.choice(some_exceptions)
    print(f'raising {choice}')
    if choice:
        raise Exception('An Error') # Don't understand the need for the 'An Error' argument
except ValueError:
    print('Caught a ValueError')
except TypeError:
    print('Caught a TypeError')
except Exception as e:
    print(f'Caught some other error: {e.__class__.__name__}')
else:
    print('This code is called if there is no exception')
finally:
    print('This code is always called')

It is just the common usage.这只是常见的用法。 Exceptions (derived from BaseException ) have an args member which contains the parameters passed at creation time, so they can accept 0 to n parameters.异常(从BaseException派生)有一个args成员,其中包含在创建时传递的参数,因此它们可以接受 0 到 n 个参数。 Nevertheless the doc for BaseException.args says (emphasize mine):不过BaseException.args的文档说(强调我的):

The tuple of arguments given to the exception constructor.给异常构造函数的 arguments 元组。 Some built-in exceptions (like OSError) expect a certain number of arguments and assign a special meaning to the elements of this tuple, while others are usually called only with a single string giving an error message.一些内置异常(如 OSError)需要一定数量的 arguments 并为该元组的元素分配特殊含义,而其他异常通常仅使用单个字符串调用并给出错误消息。

These both are type errors (in native python), but see how the custom message is different这些都是类型错误(在本机 python 中),但请查看自定义消息有何不同

>>> a = [1,2,3]
>>> a['d']

TypeError: list indices must be integers or slices, not str

>>> 1 in 'fs'

TypeError: 'in <string>' requires string as left operand, not int

And so, to generate a custom error message which is subset of an existing class you can do this:因此,要生成作为现有 class 子集的自定义错误消息,您可以执行以下操作:

>>> raise TypeError('meaningless type error')

TypeError: meaningless type error

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM