如何处理 class 方法中的异常?

how to handle exceptions inside a class method?

我正在尝试在 class 方法中处理异常,想法是如果遇到异常,则该方法必须执行一些操作并传递给另一个值。

这是我目前得到的结果:

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

应用时:

# applying #
values=[1,None,3]      
  
if __name__=="__main__":
    
     just_a_class = test_class()
     for value in values:
         just_a_class.applying_function(value)

下一个错误出现:

TypeError: catching classes that do not inherit from BaseException is not allowed

是否有任何方法可以将 applying_function() 转换为一种形式,如果 None 则忽略该值并继续,预期输出可能如下所示:

#1
#No value
#3

您在 try except 中传递了一个实例化错误。相反你应该有:

try:
   self.just_a_function(value)
except TypeError as e:
   pass

except 需要类型而不是实例化对象。