顺 达 代 理 呦

  顺 达 代 理 呦-qQ同步【32384】【32384】信誉至上【待遇,一步到位】直接添加无需打开.每个异常都是一些类的实例,这些实例可以被引发,并且可以用很多方法进行捕捉,使得程序可以捉住错误并对其进行处理,而不是让整个程序失败。
  
  按自己的方式出错
  
  异常可以在某些东西出错时自动引发。
  
  raise语句
  
  顺 达 代 理 呦-qQ同步【32384】【32384】信誉至上【待遇,一步到位】直接添加无需打开.为了引发异常,可以使用一个类(应该是Exception的子类)或者实例参数调用raise语句。使用类时,程序会自动创建实例。
  
  >>> raise Exception
  
  Traceback (most recent call last):
  
  File "<pyshell#1>", line 1, in <module>
  
  raise Exception
  
  Exception
  
  >>> raise Exception(‘hyperdrive overload‘)
  
  Traceback (most recent call last):
  
  File "<pyshell#2>", line 1, in <module>
  
  raise Exception(‘hyperdrive overload‘)
  
  Exception: hyperdrive overload
  
  第一个例子引发了一个没有任何有关错误信息的普通异常;
  
  第二个例子则添加了一些hyperdive overload错误信息。
  
  内建的异常类有很多。
  
  >>> import exceptions
  
  >>> dir(exceptions)
  
  [‘ArithmeticError‘, ‘AssertionError‘, ‘AttributeError‘, ‘BaseException‘, ‘BufferError‘, ‘BytesWarning‘, ‘DeprecationWarning‘, ‘EOFError‘, ‘EnvironmentError‘, ‘Exception‘, ‘FloatingPointError‘, ‘FutureWarning‘, ‘GeneratorExit‘, ‘IOError‘, ‘ImportError‘, ‘ImportWarning‘, ‘IndentationError‘, ‘IndexError‘, ‘KeyError‘, ‘KeyboardInterrupt‘, ‘LookupError‘, ‘MemoryError‘, ‘NameError‘, ‘NotImplementedError‘, ‘OSError‘, ‘OverflowError‘, ‘PendingDeprecationWarning‘, ‘ReferenceError‘, ‘RuntimeError‘, ‘RuntimeWarning‘, ‘StandardError‘, ‘StopIteration‘, ‘SyntaxError‘, ‘SyntaxWarning‘, ‘SystemError‘, ‘SystemExit‘, ‘TabError‘, ‘TypeError‘, ‘UnboundLocalError‘, ‘UnicodeDecodeError‘, ‘UnicodeEncodeError‘, ‘UnicodeError‘, ‘UnicodeTranslateError‘, ‘UnicodeWarning‘, ‘UserWarning‘, ‘ValueError‘, ‘Warning‘, ‘WindowsError‘, ‘ZeroDivisionError‘, ‘__doc__‘, ‘__name__‘, ‘__package__‘]
  
  所有这些异常都可以用于raise语句:
  
  >>> raise ZeroDivisionError
  
  Traceback (most recent call last):
  
  File "<pyshell#6>", line 1, in <module>
  
  raise ZeroDivisionError
  
  ZeroDivisionError
  
  >>> raise BaseException
  
  Traceback (most recent call last):
  
  File "<pyshell#7>", line 1, in <module>
  
  raise BaseException
  
  BaseException
  
  一些最重要的内建异常类:
  
  类名 描述
  
  Exception 所有异常的基类
  
  AttributeError 特性引用或赋值失败时引发
  
  IOError 试图打开不存在的文件(包括其他情况)时引发
  
  IndexError 在使用序列不存在的索引时引发
  
  KeyError 在使用映射中不存在的键时引发
  
  NameError 在找不到名字(变量)时引发
  
  SyntaxError 在代码为错误形式时引发
  
  TypeError 在内建操作或函数应用于错误类型的对象时引发
  
  ValueError 在内建操作或者函数应用于正确类型的对象,但该对象使用不合适的值时引发
  
  ZeroDivisionError 在除法或模除操作的第二个参数为0时引发
  
  自定义异常类
  
  有些时候需要创建自己的异常类。
  
  class SomeCustomException(Exception): pass
  
  顺 达 代 理 呦-qQ同步【32384】【32384】信誉至上【待遇,一步到位】直接添加无需打开.可以向自动义异常类中增加方法,此处什么也没做。

猜你喜欢

转载自www.cnblogs.com/huhz1979/p/12791327.html