[英]How to raise own error when one argument is missing?
Hi I'm pretty new to Python and I've just started to learn about errors and exceptions.I have this function in a class that inserts a line at a given index called num.I know python will raise an error if no num is given but I want to raise my own error.How do I do that?This is what I tried. 嗨,我是Python的新手,我刚刚开始学习错误和异常。我在一个类中有此函数,该类在给定索引num处插入一行。我知道python如果没有num会引发错误给定但我想提出自己的错误我该怎么做? But the error raised is still the default error?
但是引发的错误仍然是默认错误吗?
def insertNum(self, num, line):
if num== None:
raise Exception("Num not specified.")
else:
self.list.insert(num, line)
return self.list
You can set the default value of num
to None
and then check if the value is None
. 您可以将
num
的默认值设置为None
,然后检查该值是否为None
。
def insertNum(self, line, num=None):
if num is None:
raise Exception("Num not specified.")
else:
self.list.insert(num, line)
return self.list
If you pass only one parameter to the insertNum
method, num
will be set the None
(the default value) and will raise the exception. 如果仅将一个参数传递给
insertNum
方法,则会将num
设置为None
(默认值),并将引发异常。
If you don't want to change the order of the arguments, you can use this: 如果您不想更改参数的顺序,则可以使用以下命令:
def insertNum(self, num, line=None):
if line is None:
raise Exception("Num not specified.")
else:
self.list.insert(num, line)
return self.list
A simple demonstration for how default arguments work: 关于默认参数如何工作的简单演示:
>>> def foo(bar, baz=None):
... print(bar, baz)
...
>>> foo(1, 2)
1 2
>>> foo(2)
2 None
I suggest you read about exceptions and errors 我建议您阅读有关异常和错误的信息
But the main idea is that you catch errors and then you handle them the way you like. 但是主要的想法是先发现错误,然后以自己喜欢的方式处理它们。
try:
#do something
except Exception as e:
# error occured
print("A wild error appeared")
You can use try...except
statement. 您可以使用
try...except
语句。
def insertNum(num, line):
try:
list.insert(num, line)
return list
except:
print('custom error')
wrap your function with another function that will have try
and except` and there you could raise what ever error/exception you want. 用另一个带有
try
和except`的函数包装您的函数,在那里您可以引发任何想要的错误/异常。
def wrapper_func(self, num, line):
try:
self.insertNum(num, line)
except Exception as e:
raise Exception("whatever you want")
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.