python学习[第十六篇] 异常

python学习[第十六篇] 异常

python中的异常

NameError 尝试访问一个未声明的变量

ZeroDivisionError 除数为0

SyntaxError pyhton解释器语法错误

IndexError 索引超出范围

KeyError 请求一个不存在的字典关键字

IOError 输入输出错误

AttributeError 尝试访问未知的对象属性

#NameError
>>> i
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'i' is not defined

#ZeroDivisionError
>>> 1/0
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ZeroDivisionError: integer division or modulo by zero

#SyntaxError
>>> x=2
>>> x++
  File "<stdin>", line 1
    x++
      ^
SyntaxError: invalid syntax

#IndexError
>>> x=[1]
>>> x[2]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
IndexError: list index out of range

#KeyError
>>> x={1:2}
>>> x[2]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
KeyError: 2

#IOError
>>> x=open('a')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
IOError: [Errno 2] No such file or directory: 'a'

#AttributeError
>>> x.__ooo___
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'dict' object has no attribute '__ooo___'

检测和处理异常

异常通过try方法来捕获

主要有两种方式:try-except 和try-finally。一个try语句可以对应多个except语句,但只能对应一个finally语句,或是一个try-except-finally语句。

try-except语句

#一个except 只处理一个Exception
try:
    try_suite
except Exception,[reason]:
    except_suite
#一个except 处理多个Exception
try:
    try_suite
except Exception1,[exception2],...,[exceptionN],[reason]:
    except_suite
# 多个except处理多个Exception
try:
    try_suite
except Exception1,[exception2],...,[exceptionN],[reason]:
    except_suite
except Exception1,[exception2],...,[exceptionN],[reason]:
    except_suite
except Exception1,[exception2],...,[exceptionN],[reason]:
    except_suite

捕获所有的异常

python 异常结构

  • BaseException
  •     |-----KeyboardInterrupt
  •     |-----SystemExit
  •     |-----Exception
  •         |-----(all other current built-in exception)
try:
    try_suite
except Exception,e:
    except_suite
try:
    try_suite
except BaseException:
    except_suite

异常参数

我们可以在except 语句后面加一个参数,参数会包含来自导致异常的代码诊断信息。是一个类的实例。

>>> try:
...     f=open('test.txt','r')
... except IOError,e:
...     type(e)
...     print e
...
<type 'exceptions.IOError'>
[Errno 2] No such file or directory: 'test.txt'

 

else子句

在try 范围中没有异常检测到时,会执行else子句。

>>> try:
...     x='ttt'
... except Exception,e:
...     print e
... else:
...     print x
...
ttt

 

finally子句

finally子句无论异常是否会发生,都会执行finally子句。try必须有一个except ,else和finally 可有可无。

try:
    A
except:
    B
else:
    C
finally:
    D

 

触发异常

python使用raise来触发异常

异常和sys模块

我们可以通过sys模块中的exc_info()函数来获取异常信息。此功能返回一个3元组

>>> try:
...     float('test')
... except:
...     import sys
...     exc_typle=sys.exc_info()
...     print exc_typle
...
(<type 'exceptions.ValueError'>, 
ValueError('could not convert string to float:test',),
 <traceback object at 0x02619990>)

 

转载于:https://www.cnblogs.com/ryanpan/p/9376391.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值