Python异常

if 和 异常

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

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

try:
    x = input('Enter the 1st num: ')
    y = input('Enter the 2nd num: ')
    print x/y
except 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.arrti
except 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:# 适合程序内部使用
                raise

cal = 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/y
except Exception,e: # 不可能捕获所有异常,这种方式比较好
# except:print 'something wrong'  这种方式很危险最好不用:用户的ctrl+c / sys.exit
    print e
'''方法1
except (ZeroDivisionError,TypeError),e:
    print e # 访问异常对象本身
'''
'''方法2
except (ZeroDivisionError,TypeError,NameError):
    print 'Your input is not legal,check please!'
'''
'''方法3
except 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
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值