为什么错误处理不适用于None输入?

时间:2015-10-27 14:53:53

标签: python

def copy_list(t):
try:
    if type(t) is list:
        t_copy=[]
        n=len(t)
        i=0
        while i<n:
            t_copy.append(t[i])
            i+=1
        return t_copy
except TypeError:
        return "Not a list"

问题是我应该编写一个函数,它将整数列表作为输入并返回它的副本。如果输入不是列表,它应该引发异常。 我无法理解为什么我的代码无法引发异常,如果该值不是列表类型或输入为None?

3 个答案:

答案 0 :(得分:0)

您的代码不会引发异常,因为您使用t检查if type(t) is list的类型是否为列表。当您提供None作为输入时,它不会传递if语句并通过,因此不会返回任何内容,也不会引发异常。

您可以删除if语句以引发异常。 n=len(t)会触发异常,因为您无法获得None的长度(TypeError: object of type 'NoneType' has no len() ),并且会返回"Not a list"

try:
    t_copy=[]
    n=len(t)
    i=0
    while i<n:
        t_copy.append(t[i])
        i+=1
    return t_copy
except TypeError:
    return "Not a list"

答案 1 :(得分:0)

将它扔进this.methodName循环,for应该抓住其他任何内容。

if type

或者更简洁:

def copy_list(t):
    if type(t) is list:
        t_copy=[]
        for i in t:
            t_copy.append(i)
        return t_copy
    else:
        return "Not a list"
y = None
x = copy_list(y)
print x
y = "abc"
x = copy_list(y)
print x
y = [1,2,3,4,5,6,7,8,9]
x = copy_list(y)
print x

结果:

def copy_list(t):
    if type(t) is list:
        t_copy = list(t)
        return t_copy
    else:
        return "Not a list"
y = ""
x = copy_list(y)
print x,"\t", type(y)
y = []
x = copy_list(y)
print x,"\t\t", type(y)
y = None
x = copy_list(y)
print x,"   ", type(y)
y = 10
x = copy_list(y)
print x,"   ", type(y)
y = "abc"
x = copy_list(y)
print x,"   ", type(y)
y = [1,2,3,4]
x = copy_list(y)
print x,"   ", type(y)
y = ["a",2,"b"]
x = copy_list(y)
print x,"   ", type(y)
y = {'Name': 'Zara', 'Age': 7, 'Class': 'First'}
x = copy_list(y)
print x,"   ", type(y)     

答案 2 :(得分:0)

try / except块用于优雅地处理遇到意外或非法值时解释器抛出的异常,而不是故意引发异常。为此,您需要raise关键字。请参阅此问题:How to use "raise" keyword in Python

作为建议,您的代码可能如下所示:

def copy_list(t):
    if isinstance(t, list):
        t_copy=[]
        n=len(t)
        i=0
        while i<n:
            t_copy.append(t[i])
            i+=1
        return t_copy
    else:
        raise Exception('Not a list')

编辑:我认为你也想要isinstance功能,我已经相应地编辑了代码。可以找到here的信息。