Why is the error handling not working for None input?
1 2 3 4 5 6 7 8 9 10 11 12 | 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" |
问题是,我应该编写一个函数,它将整数列表作为输入,并返回一个整数的副本。如果输入不是列表,则应引发异常。我无法理解,如果值不是列表类型或输入为"无",为什么我的代码无法引发异常?
Try/Except块用于在遇到意外或非法值时优雅地处理解释器引发的异常,而不是有意引发异常。为此,您需要
作为建议,您的代码可能如下所示:
1 2 3 4 5 6 7 8 9 10 11 | 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') |
编辑:我认为您还需要
只要把它扔到一个
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | 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 |
或者更简洁地说:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 | 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) |
结果:
1 2 3 4 5 6 7 8 | Not a list <type 'str'> [] <type 'list'> Not a list <type 'NoneType'> Not a list <type 'int'> Not a list <type 'str'> [1, 2, 3, 4] <type 'list'> ['a', 2, 'b'] <type 'list'> Not a list <type 'dict'> |
您的代码不会引发异常,因为您检查
您可以删除
)
1 2 3 4 5 6 7 8 9 10 | 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" |