码迷,mamicode.com
首页 > 编程语言 > 详细

python笔记--异常处理

时间:2017-05-24 22:31:17      阅读:160      评论:0      收藏:0      [点我收藏+]

标签: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 "<pyshell#27>", 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组合语句,需要注意的是elsefinally都要放在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 "<pyshell#2>", 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             #添加一个"message"属性,用于存放错误信息
    def __str__(self):
        return self.message
 

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

myerror!

6.断言语句assert

assert用于判断条件判断语句是否为真,不为真则处罚异常,例如:

>>> assert 2>1
>>> assert 2<1


Traceback (most recent call last):
  File "<pyshell#22>", line 1, in <module>
    assert 2<1
AssertionError

#添加异常描述信息:

>>> assert 2<1,"flase"
 
Traceback (most recent call last):
  File "<pyshell#23>", line 1, in <module>
    assert 2<1,"flase"
AssertionError: flase

 

本文出自 “网络技术” 博客,请务必保留此出处http://fengjicheng.blog.51cto.com/11891287/1929107

python笔记--异常处理

标签:python、异常处理

原文地址:http://fengjicheng.blog.51cto.com/11891287/1929107

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!