Soo*_*Lim 5 python error-handling exception
你好,我对 Python 很陌生,我刚刚开始学习错误和异常。我在一个类中有这个函数,它在给定索引处插入一行名为 num 的行。我知道如果没有 num,Python 会引发错误给定,但我想提出我自己的错误。我该怎么做?这就是我尝试过的。但引发的错误仍然是默认错误?
def insertNum(self, num, line):
if num== None:
raise Exception("Num not specified.")
else:
self.list.insert(num, line)
return self.list
Run Code Online (Sandbox Code Playgroud)
您可以使用try...except声明。
def insertNum(num, line):
try:
list.insert(num, line)
return list
except:
print('custom error')
Run Code Online (Sandbox Code Playgroud)