【问题标题】:list of custom defined exceptions. How to create such a list?自定义异常列表。如何创建这样的列表?
【发布时间】:2014-08-15 13:51:02
【问题描述】:

有什么方法可以将用户定义的异常(我们自定义的异常)存储在列表中?因此,如果发生任何其他不在列表中的异常.. 程序应该简单地中止。

【问题讨论】:

    标签: python exception exception-handling abort custom-exceptions


    【解决方案1】:

    单个except 可能有多个错误,自定义或其他错误:

    >>> class MyError(Exception):
        pass
    
    >>> try:
        int("foo") # will raise ValueError
    except (MyError, ValueError):
        print "Thought this might happen"
    except Exception:
        print "Didn't think that would happen"
    
    
    Thought this might happen
    >>> try:
        1 / 0 # will raise ZeroDivisionError
    except (MyError, ValueError):
        print "Thought this might happen"
    except Exception:
        print "Didn't think that would happen"
    
    
    Didn't think that would happen
    

    【讨论】:

      【解决方案2】:

      通常的方法是使用异常层次结构。

      class OurError(Exception):
          pass
      
      class PotatoError(OurError):
          pass
      
      class SpamError(OurError):
          pass
      
      # As many more as you like ...
      

      然后您只需在 except 块中捕获 OurError,而不是尝试捕获它们的元组或具有多个 except 块。


      当然,实际上没有什么可以阻止您将它们存储在您提到的列表中:

      >>> our_exceptions = [ValueError, TypeError]
      >>> try:
      ...    1 + 'a'
      ... except tuple(our_exceptions) as the_error:
      ...    print 'caught {}'.format(the_error.__class__)
      ...     
      caught <type 'exceptions.TypeError'>
      

      【讨论】:

      • 在这种情况下,我希望实现的是 ValueError 或 TypeError 'ONLY THEN' 我想报告相应的错误消息。对于其余所有错误,我只想执行 exit(1)。我正在想办法做到这一点。
      • 一个未处理的异常已经这样做了(死)。如果要自定义“崩溃”行为,可以添加另一个裸 except: 块和 sys.exit() 或其他任何内容
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-07-12
      • 1970-01-01
      • 1970-01-01
      • 2014-12-10
      • 1970-01-01
      相关资源
      最近更新 更多