Python异常

来源:互联网 发布:腾牛网软件 编辑:程序博客网 时间:2024/06/07 21:13

if 和 异常

或许使用 if 可以处理一些意外,可能每个情况都要涉及,但是异常可以处理很多意外而只需要很少的错误处理,异常则可以处理一类情况。

同时,异常处理不会将代码弄乱,只需要在后面加上一些类型的异常捕获即可,但if 检查则可能会增加 很多条件。

try:    x = input('Enter the 1st num: ')    y = input('Enter the 2nd num: ')    print x/yexcept ZeroDivisionError:    print 'The 2nd number can not be zero!'except TypeError:    print 'It was not number?'
上述的except 后面都是一些内建异常类

# -*- coding: utf-8 -*-  def describePerson(person):    print 'Description of',person['name']    if 'occupation' in person: # 这里检查一次,执行两次occupation键查找        print 'Occupation is',person['occupation'] # 再执行一次def describePerson(person):    print 'Description of',person['name']    try:        print 'Occupation is',person['occupation']  # 执行一次    except KeyError:pass

查看对象是否存在某属性:

# -*- coding: utf-8 -*-  try: # 联想 getattr    obj.arrtiexcept AttributeError:    print 'No attribute'else:    print 'Attribute exist'

传播异常:raise

如果没有捕捉异常,他就会传播到调用的函数中,如果捕捉到了异常又想重新引发,可以使用raise。

# -*- coding: utf-8 -*-  class MuffledCalculator:    muffled = False # 默认不屏蔽    def calc(self, expr):        try:            return eval(expr)        except ZeroDivisionError:            if self.muffled:                print 'Division by zero is illegal' # 使用屏蔽机制,函数返回None            else:# 适合程序内部使用                raisecal = MuffledCalculator()cal.calc('10/0') # 没有打开屏蔽机制,异常传播cal.muffled = True # 适合用户交互,打印错误信息不让异常传播cal.calc('10/0')


捕捉多个异常

except 后面最好跟上你设想的异常类型

# -*- coding: utf-8 -*-  try:    x = input('Enter the 1st num: ')    y = input('Enter the 2nd num: ')    print x/yexcept Exception,e: # 不可能捕获所有异常,这种方式比较好# except:print 'something wrong'  这种方式很危险最好不用:用户的ctrl+c / sys.exit    print e'''方法1except (ZeroDivisionError,TypeError),e:    print e # 访问异常对象本身''''''方法2except (ZeroDivisionError,TypeError,NameError):    print 'Your input is not legal,check please!'''''''方法3except ZeroDivisionError:    print 'The 2nd number can not be zero!'except TypeError:    print 'It was not number?''''
将异常整合为元组作为except 的参数 / 使用 Exception(内建异常模块) 


使用else,final 让处理更全面

只要有错误就会持续运行到没有错误为止

# -*- coding: utf-8 -*-  while True:    try:        x = input('Enter the 1st num: ')        y = input('Enter the 2nd num: ')        print x/y    except Exception,e:        print e,',Try again!'    else:        break

而 final 一般负责异常后的清理,不管异常是否发生,都会被执行,final用于关闭文件或者网络套接字使有用。



0 0
原创粉丝点击