python 异常处理

try\except\finally
标准内置except error: https://www.runoob.com/python/python-exceptions.html
(1)使用标准except输出error。finally语句一定会执行,引发异常后会跳出try语句继续执行下面代码。

# -*- coding: utf-8 -*-
import traceback
flag=True
file = "C:\\Users\\RSGIS201-4\\Desktop\\test1.csv"
while flag:
    try:
        flag = False
        f = open(file)
        print f
        assert 1==2

    except IOError,Argument:
        print Argument
        file = "C:\\Users\\RSGIS201-4\\Desktop\\test.csv"
        flag=True
        #使用traceback将错误信息输出到控制台和txt
        traceback.print_exc()
        f0 = open("C:\\Users\\RSGIS201-4\\Desktop\\1.txt", 'a')
        traceback.print_exc(file=f0)
        f0.flush()
        f0.close()
        # 使用logging将错误信息输出到控制台和txt
    except AssertionError :
        print "AssertionError"

    finally:
        print "先执行finay还是exce"

(2)自定义except。所有异常的基类都是BaseException.

class TooLongExceptin():  #自定义异常
    "this is user's Exception for check the length of name "

    def __init__(self, leng):
        self.leng = leng

    def __str__(self):  
        return "姓名长度是" + str(self.leng) + ",超过长度了"

name="dsvbailf"
try:
    if len(name) > 4:
        raise TooLongExceptin(len(name))   #自定义抛出异常
    print "why?"

except TooLongExceptin,b:  #捕捉异常
    print b   ##bTooLongExceptin的实例,print 会自动调用 __str__函数。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值