yesn 发表于 2018-8-14 11:10:28

python笔记--异常处理

  异常处理
  异常就是程序出现错误无法正常工作了,异常处理是通过一些方法对出现的错误进行捕捉,友好地显示出来或进行相应的处理,使得程序能够更长时间运行。
  1.异常种类
  常见的:
  SyntaxError          语法错误
  IndentationError缩进错误
  TypeError            对象类型与要求不符合
  ImportError          模块或包导入错误;一般路径或名称错误
  KeyError             字典里面不存在的键
  NameError            变量不存在
  IndexError         下标超出序列范围
  IOError            输入/输出异常;一般是无法打开文件
  AttributeError       对象里没有属性
  KeyboardInterrupt键盘接受到 Ctrl+C
  Exception            通用的异常类型;一般会捕捉所有异常
  查看所有的异常种类:
>>> 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__']
  2.捕捉异常语法
try:  
pass               #被检查的语句
  
except except type,e:    #except type表示要捕捉的异常种类,e是一个变量,保存了异常信息。
  
pass               #”,e”可以写成”as e”
  例如:
>>> try:  
print a    #a是一个未定义的变量,直接执行”print a”会报NameError异常
  
except NameError,e:
  
print "Error:",e
  

  

  
Error: name 'a' is not defined
  注意:
  如果异常可能会出现多个种类,可以写多个except。例如:
>>> a = 'hello'  
>>> try:
  
    int(a)
  
except IndexError,e:
  
    print e
  
except KeyError,e:
  
    print e
  
except ValueError,e:
  
print e
  如果不知道会出现什么异常,可以使用Exception捕获任意异常,例如:
>>> a='hello'  
>>> try:
  
    int(a)
  
except Exception,e:
  
    print e
  如果未捕获到异常即异常种类不匹配,程序直接报错,例如:
>>> a='hello'  
>>> try:
  
b=int(a)
  
except IndexError,e:
  
print e
  

  

  

  
Traceback (most recent call last):
  
File &quot;<pyshell#27>&quot;, line 2, in <module>
  
    b=int(a)
  
ValueError: invalid literal for int() with base 10: 'hello'
  捕捉异常的其他结构:
  #else语句
try:  
    pass    #主代码块
  
except KeyError,e:
  
    pass
  
else:
  
    pass    # 主代码块执行完没有异常,执行该块。
  #finally语句
try:  
    pass    #主代码块
  
except KeyError,e:
  
    pass
  
finally:
  
    pass    # 无论异常与否,最终都执行该块。
  #try/except/else/finally组合语句,需要注意的是else和finally都要放在except之后,而finally要放在最后。
try:  
    pass
  
except KeyError,e:
  
    pass
  
else:
  
    pass
  
finally:
  
    pass
  4. 主动触发异常
  raise可以主动抛出一个异常,例如:
>>> raise NameError('this is an NameError')  

  
Traceback (most recent call last):
  
File &quot;<pyshell#2>&quot;, line 1, in <module>
  
    raise NameError('this is an NameError')
  
NameError: this is an NameError
  #捕捉主动触发的异常
>>> try:  
    raise Exception('error!!!')
  
except Exception,e:
  
    print e
  

  

  
error!!!
  5.自定义异常
>>> class MyException(Exception):    #继承Exception类  
    def __init__(self,msg):          #使用Exception类的__init__方法
  
      self.message=msg             #添加一个&quot;message&quot;属性,用于存放错误信息
  
    def __str__(self):
  
      return self.message
  

  

  
>>> try:
  
    raise MyException(&quot;myerror!&quot;)    #主动引发自定义异常
  
except MyException,e:
  
    print e
  

  

  
myerror!
  6.断言语句assert
  assert用于判断条件判断语句是否为真,不为真则处罚异常,例如:
>>> assert 2>1  
>>> assert 2<1
  

  

  
Traceback (most recent call last):
  
File &quot;<pyshell#22>&quot;, line 1, in <module>
  
    assert 2<1
  
AssertionError
  #添加异常描述信息:
>>> assert 2<1,&quot;flase&quot;  

  
Traceback (most recent call last):
  
File &quot;<pyshell#23>&quot;, line 1, in <module>
  
    assert 2<1,&quot;flase&quot;
  
AssertionError: flase
  7.traceback模块
  在以上例子中,最后都是print打印出了异常信息,虽然可以获得异常类型,但是无法看到具体是哪一行代码异常。使用traceback模块,既可以看到异常类型,又可以得到是异常代码位置,例如:
>>> import traceback  
>>> try:
  
...   1/0
  
... except Exception as e:
  
...   traceback.print_exc()
  
...
  
Traceback (most recent call last):
  
File &quot;<stdin>&quot;, line 2, in <module>
  
ZeroDivisionError: division by zero
页: [1]
查看完整版本: python笔记--异常处理