【再回首Python之美】【异常处理】try-except

本文探讨了Python中异常处理的重要性,介绍了如何使用try-except捕获和处理异常,包括捕获所有异常、特定异常及多个异常的情况。通过示例代码展示,强调了异常处理对程序健壮性的影响,防止程序因异常而意外终止。
摘要由CSDN通过智能技术生成

使用方法直接跳看:推荐使用的异常处理流程;推荐的内建函数的封装函数

异常处理必要性

     为了保证程序的健壮性,将可能出现异常退出的代码用try……except来处理

捕获异常的各种方法

    1.捕获所有异常

print "\r\n=======try-except========="
try:
    open('unexistFile')
except:
    print "failed to open."

    2.捕获特殊异常,如ctrl+c等

    KeyboardInterrupt和SystemExit,是与Exception平级的异常。

print '\r\n======try-except (KeyboardInterupt, SystemExit)======'
try:
    while 1:
        pass
except (KeyboardInterrupt, SystemExit):#ctrl+c等导致app退出异常
    print 'app will exit, handle app exitence.'

    3.捕获具体异常,1/0等

print "\r\n======try-except ZeroDivisionError,e======="
try:
    1/0 #除数为零
except ZeroDivisionError, e:
    print 'ZeroDivisionError:',e

    4.捕获多个具体的异常

#try-except (E1, E2,……En)[,e]:捕获多个异常
print '\r\n======try-except (E1, E2,……En)[,e]======'
try:
    1/0
except (NameError,ZeroDivisionError),e:
    print repr(e)

    5.待追加

简单示例代码

#ex_except.py

def dumpFile_withExcept(path):
    try:
        f = file(path)
        print 'Succeed open file'
        f.close()
    except:
        print 'Failed open file, file not exists.'
        return False
    return True

def dumpFile_nonExcept(path):
    f = file(path)
    f.close()
    
#test
dumpFile_withExcept('non-exist.txt')
dumpFile_nonExcept('non-exist.txt')
编译执行

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值