如何在Python中使用if语句抛出TypeError错误消息?

问题描述 投票:2回答:2

我想做什么

我想修正当前代码以通过编码挑战Codewars Prefill an Array

在这种情况下,我希望学习如何在带有if语句的消息中引发TypeError。

创建函数预填充,该函数返回包含n个具有相同值v的n个元素的数组。看看是否可以在不使用循环的情况下执行此操作。

您必须验证输入:如果省略了v,则v可以是任何值(原始或其他方式);如果n为0,则用undefined填充数组;如果n是除整数或整数格式的字符串以外的其他值,则返回一个空数组(例如'123')(即> = 0,抛出TypeError

引发TypeError时,消息应为n无效,其中您将n替换为传递给函数的实际值。

Code Examples
    prefill(3,1) --> [1,1,1]

    prefill(2,"abc") --> ['abc','abc']

    prefill("1", 1) --> [1]

    prefill(3, prefill(2,'2d'))
      --> [['2d','2d'],['2d','2d'],['2d','2d']]

    prefill("xyz", 1)
      --> throws TypeError with message "xyz is invalid"

问题

我在5个样本测试中通过了4个样本测试,但我不能通过以下一个。

    prefill("xyz", 1)
      --> throws TypeError with message "xyz is invalid"

错误消息

Traceback (most recent call last): File "main.py", line 8,
in <module> prefill('xyz', 1) File "/home/codewarrior/solution.py", 
line 3, in prefill if int(n): ValueError: invalid literal for int() with base 10: 'xyz'

当前代码

def prefill(n,v):

    if int(n):
        result = [0] * int(n)
        for i in range(len(result)):
            result[i] = v
        return result

    else:
        return TypeError, str(n) + "is invalid"

开发环境

Python 3.4.3

python python-3.x algorithm exception
2个回答
1
投票

您可以使用try-except捕获错误,并抛出另一个错误:

def prefill(n,v):
    try:
        n = int(n)
    except ValueError:
        raise TypeError("{0} is invalid".format(n))
    else:
        return [v] * n

例如:

>>> prefill(3,1)
[1, 1, 1]
>>> prefill(2,"abc")
['abc', 'abc']
>>> prefill("1", 1)
[1]
>>> prefill(3, prefill(2,'2d'))
[['2d', '2d'], ['2d', '2d'], ['2d', '2d']]
>>> prefill("xyz", 1)
Traceback (most recent call last):
  File "<stdin>", line 1, in prefill
ValueError: invalid literal for int() with base 10: 'xyz'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 1, in prefill
TypeError: xyz is invalid

1
投票

使用raise关键字引发异常,而不是返回异常。 raise用于生成新的异常:

>>> raise TypeError
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError

在此示例中,我直接使用异常类引发了TypeError。您也可以像这样创建错误的实例:

>>> t=TypeError()
>>> raise t
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError

通过这种方式,可以在使用raise之前在对象上设置各种属性。发布的问题包括此要求:

引发TypeError时,消息应该是n无效,在这里您将n替换为传递给函数的实际值。

这是在使用raise之前必须先创建错误的实例,然后在其上设置message属性的情况的示例。

© www.soinside.com 2019 - 2024. All rights reserved.