[英]how to handle exceptions inside a class method?
I am trying to handle an exception inside a class method, the idea is that if the exception is met then the method has to do some stuff and pass to another value.我正在尝试处理 class 方法中的异常,其想法是,如果遇到异常,则该方法必须做一些事情并传递给另一个值。
Here's what I got so far:这是我到目前为止得到的:
class test_class():
def just_a_function(self, value):
if value is None:
print('No value')
raise TypeError('No value')
else:
print(value)
def applying_function(self, value):
# doing some stuff like print('something')
try:
self.just_a_function(value)
except TypeError('No value'):
# do some other stuff like print('other options')
pass
When applied:应用时:
# applying #
values=[1,None,3]
if __name__=="__main__":
just_a_class = test_class()
for value in values:
just_a_class.applying_function(value)
The next error arises:出现下一个错误:
TypeError: catching classes that do not inherit from BaseException is not allowed TypeError:不允许捕获不继承自 BaseException 的类
Is there any way to transform applying_function()
in a form that if None
then just ignore the value and continue, in a way that expected output could look like this:有没有办法以一种形式转换applying_function()
,如果None
然后忽略该值并继续,以预期 output 可能如下所示的方式:
#1
#No value
#3
You are passing an instantiated error in your try except.您在尝试中传递了一个实例化错误,除了。 Instead you should have:相反,您应该拥有:
try:
self.just_a_function(value)
except TypeError as e:
pass
except
expects a type and not an instantiated object. except
需要一个类型而不是实例化的 object。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.