Note_python(03)

错误与异常

  • AttributeError:尝试访问未知的对象属性
eg. 
>>> class myClass(object):
...     pass
...
>>> my = myClass()
>>> my.name = 'Yanta'
>>> my.name
'Yanta'
>>> my.age
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'myClass' object has no attribute 'age'

检测与处理异常

异常通过try语句检测,任何在try语句块里的代码都会被检测,检查有无异常发生
try语句有两种主要形式:try-except和try-finally. 这两个语句是互斥的,也就是说你只能使用其中的一种。一个try语句可以对应一个或者多个except语句,但是只能对应一个finally语句,或者一个try-except-finally复合语句。
也就是说:以下三种形式任选其一。

1try-except
2try-finally
3try-except-finally

其中可以使用try-except语句检测和处理异常,也可以添加一个可选的else子句处理没有探测到异常的执行的代码。
try-finally只允许检测异常并作一些必要的清除工作(无论发生错误与否),没有任何异常处理措施。
复合语句,两者都可以做到。

try-except

try-except语句定义了进行异常监控的一段代码,并且提供了异常处理的机制。
语法形式:

try:
    try_suite        #监控这里的异常
except Expection[, reason]:
    expect_suite      #异常处理代码

eg.

>>> try:
...     os.remove('test01.log')
... except IOError, e:
...     print 'Could not remove the file:', e
...
Traceback (most recent call last):
  File "<stdin>", line 2, in <module>
OSError: [Errno 2] No such file or directory: 'test01.log' #异常报错

处理多个异常的try-except语句:

>>> try:
...     os.remove('test01.log')
... except OSError, e:
...     print 'No such file or directory: ', e
... except TypeError, e:
...     print 'Type argument Error: ', e
...
No such file or directory:  [Errno 2] No such file or directory: 'test01.log'

捕获所有异常

1、有些异常不是由于错误条件引起的,比如:SystemExit(当前的python程序需要退出)和KeyboardInterupt(用户按下了Ctrl+C组合键)
2、python2.5之后python异常的继承发生了变化:

  - BaseException
      | - KeyboardInterupt
      | - SystemExit
      | - Exception
          | - (all other current built-in exceptions)所有当前内建异常

这样,当你有一个Exception处理器后,你不必为这两个一场创建额外的处理器。

try:
    :
except Exception, e:
    # handle real errors

如果你确实需要捕捉所有的异常,那么就需要使用BaseException:

try:
    :
except BaseException, e:
    # handle real errors

切记

不要再try_suite语段填写入一大段代码,再用一个通用的except语句过滤掉任何致命的错误,忽略他们。
try-except语句不是用来捕捉过滤所有错误然后忽略他们。

异常参数

实际上就是保存引发异常的具体信息,一般为我们上述书写的try-except与剧中的e:

>>> try:
...     os.remove('test01.log')
... except OSError, e:
...     print 'No such file or directory: ', e
... except TypeError, e:
...     print 'Type argument Error: ', e
...
No such file or directory:  [Errno 2] No such file or directory: 'test01.log'

这个e是OSError异常类的实例,可以调用他的一些属性来得到详细信息。也可以调用内置的type()str()来显示信息:

>>> type(e)
<type 'exceptions.OSError'>
>>> str(e)
"[Errno 2] No such file or directory: 'test01.log'"
>>> print e
[Errno 2] No such file or directory: 'test01.log'
>>> e
OSError(2, 'No such file or directory')
>>> e.__class__
<type 'exceptions.OSError'>
>>> e.__class__.__doc__
'OS system call failed.'
>>> e.__class__.__name__
'OSError'

else语句

在try-except语句段中,else语句只有在try范围中没有异常被检测到时,才会被执行。而且在else范围的任何代码被运行前,try范围的所有代码必须被完全执行成功。不能引发异常。
语句格式:

try:
    try_suite
except :
    except_suite
else:
    else_suite

finally语句

finally语句是无论异常是否发生,是否捕捉都会执行的一段代码。你也可以将finally语句仅仅和try配合使用,也可以与try-except语句配合使用。
其中try-finally语句是无论异常是否发生,finally代码段都会被执行。
当try代码段引发一个异常时,会马上跳转到finally语句段,然后当finally代码段被执行完毕后会继续向上一层引发异常:

>>> try:
...     os.remove('test01.log')
... finally:
...     print '无论如何这里都会被执行!'
...
无论如何这里都会被执行!
Traceback (most recent call last):
  File "<stdin>", line 2, in <module>
OSError: [Errno 2] No such file or directory: 'test01.log'
切记

若果finally代码段引发了另一个异常或者由于return、break、continue语法而终止,原来的异常将丢失而且无法重新引发。

>>> try:
...     os.remove('test01.log')
... finally:
...     os.rmdir('test')
...
Traceback (most recent call last):
  File "<stdin>", line 4, in <module>
OSError: [Errno 2] No such file or directory: 'test'
>>>

上下文管理

with语句是用来简化代码的,这与用try-except和try-finally福哦想达到的目的前后呼应。try-except和try-finally的一种特定的配合用法是保证共享的资源的唯一分配,并在任务结束时候释放它。比如文件(数据、日志、数据库等)、线程资源、简单同步、数据库连接,等等。with语句的目的就是应用在这种场景。
然而,with语句的目的在于从流程图中巴try、except和fianlly关键字和资源分配释放相关代码统统去掉,而不是像try-except-finally那样仅仅简化代码为之所用。
基本语法如下:

  with context_expr [as var]:
      with_suite

with语句涉及到一些内在的处理细节。with语句仅仅支持上下文管理协议的对象,只有内建了“上下文管理”的对象可以和with一起工作。目前支持该协议的对象有:
* file
* decimal.Context
* thread.LockType
* thread.Lock
* thread.RLock
* thread.Condition
* thread.Semaphore
* thread.BoundedSemaphore
一打开文件为例,with语句会完成准备工作,当完成操作后,会关闭文件。而且无论在这段代码的开始、中间和结尾是发生日常,都会执行清理的代码,此外文件仍会自动关闭。eg.

>>> with open('test.log', 'r') as f0:
...     for eachline in f0:
...             print eachline
...
121

weqefse

1rfewf

1rfegvd

1rfvfdfsv cb

fsdvfvc

现在我们来测试f0:

>>> f0
<closed file 'test.log', mode 'r' at 0x7fbe66a25300>
>>> type(f0)
<type 'file'>
>>> f0.closed  #文件是否被关闭
True
>>> f0.name
'test.log'
>>> f0.mode
'r'

与正常代开文件做对比:

>>> ff = open('test.log', 'r')
>>> type(ff)
<type 'file'>
>>> ff.closed   #文件是否被关闭
False
>>> ff.name
'test.log'
>>> ff.mode
'r'
>>> ff.close()
>>> ff
<closed file 'test.log', mode 'r' at 0x7fbe66a25420>
>>> type(ff)
<type 'file'>
>>> ff.name
'test.log'
>>> ff.mode
'r'
>>> ff.closed     #文件是否被关闭
True

触发异常

Python提供一种机制让程序员明确的触发异常,这就是raise语句。
raise语句的一般用法:

raise [SomeException [, args [, traceback]]]

raise语句的用法列表:

断言

断言是一套必须等价于布尔真的判定;此外发生异常也就意味着表达式为假。
断言通过assert语句来实现,测试一个表达式,如果返回值为假,则触发异常。
assert语句语法格式:

assert expression [, arguments]

示例:

>>> assert 1 == 0
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AssertionError
>>> try:
...     assert 1 == 0
... except AssertionError, e:
...     e
...
AssertionError()

python内建异常

BaseException   #所有异常的基类
SystemExit  #解释器请求退出
KeyboardInterrupt   #用户中断执行(通常是输入^C)
Exception   #常规错误的基类
StopIteration   #迭代器没有更多的值
GeneratorExit   #生成器(generator)发生异常来通知退出
StandardError   #所有的内建标准异常的基类
ArithmeticError #所有数值计算错误的基类
FloatingPointError  #浮点计算错误
OverflowError   #数值运算超出最大限制
ZeroDivisionError   #除(或取模)零 (所有数据类型)
AssertionError  #断言语句失败
AttributeError  #对象没有这个属性
EOFError    #没有内建输入,到达EOF 标记
EnvironmentError    #操作系统错误的基类
IOError #输入/输出操作失败
OSError #操作系统错误
WindowsError    #系统调用失败
ImportError #导入模块/对象失败
LookupError #无效数据查询的基类
IndexError  #序列中没有此索引(index)
KeyError    #映射中没有这个键
MemoryError #内存溢出错误(对于Python 解释器不是致命的)
NameError   #未声明/初始化对象 (没有属性)
UnboundLocalError   #访问未初始化的本地变量
ReferenceError  #弱引用(Weak reference)试图访问已经垃圾回收了的对象
RuntimeError    #一般的运行时错误
NotImplementedError #尚未实现的方法
SyntaxError Python #语法错误
IndentationError    #缩进错误
IndentationError    #缩进错误
IndentationError    #缩进错误
TabError    #Tab 和空格混用
SystemError #一般的解释器系统错误
TypeError   #对类型无效的操作
ValueError  #传入无效的参数
UnicodeError    #Unicode 相关的错误
UnicodeDecodeError  #Unicode 解码时的错误
UnicodeEncodeError  #Unicode 编码时错误
UnicodeTranslateError   #Unicode 转换时错误
Warning #警告的基类
DeprecationWarning  #关于被弃用的特征的警告
FutureWarning   #关于构造将来语义会有改变的警告
OverflowWarning  #旧的关于自动提升为长整型(long)的警告
PendingDeprecationWarning   #关于特性将会被废弃的警告
RuntimeWarning  #可疑的运行时行为(runtime behavior)的警告
SyntaxWarning   #可疑的语法的警告
UserWarning #用户代码生成的警告

异常与sys模块

另一种获取异常信息的途径是通过sys模块的exc_info()函数,其提供一个三元组的信息。

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

这个三元组中包含着三个信息:
1、异常类
2、异常类的实例
3、跟踪记录对象

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值