python中的异常

1,空的except语句将会捕捉所有的异常,可以用sys模块中取出异常名和异常的值

2,raw_input()读文件到末尾时,会引发EOFError异常,这种异常不是错误

3,finally只做清楚工作,不做异常处理

异常处理的例子:

myException="Error"


def raise1():
   raise myException, "hello"

def raise2():
   raise myException

def tryer(func):
   try:
      func()
   except myException,extraInfo:
      import  sys
      print sys.exc_type
      print "got this:",extraInfo

执行的例子:

from exc import *

tryer(raise1)
tryer(raise2)

报错:TypeError: exceptions must be old-style classes or derived from BaseException, not str

原因:In Python 2.5 and below, your code would work, as then it was allowed to raise strings as exceptions. This was a very bad decision, and so removed in 2.6.

改写后的例子:

class myException(Exception):
   pass

def raise1():
   raise myException, "hello"

def raise2():
   raise myException

def tryer(func):
   try:
      func()
   except myException,extraInfo:
      import  sys
      print sys.exc_type
      print "got this:",extraInfo

让自己编写的异常类全部继承于Exception顶级异常类就行了


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值