pychon异常处理、异常的传递、try嵌套、自定义异常

异常

  1. 如果捕获到异常,异常下面的代码将不会执行
    as e: 可以拿到异常的信息描述
# 可以在except中处理异常,使下一次能正常运行
try:
    f = open('yang.txt', "r")
    print(f.read())
    f.close()
except FileNotFoundError:
    '可以在except处理异常,以免下次出现相同问题'
    print("FileNotFoundError!!!")
    f = open('yang.txt', "w")
    f.write('hello yang!')
    f.close()

Exception捕获所有异常

try:
    f = open('file.txt', 'r')
    f.read()
except Exception as e:
    print(e)
# >[Errno 2] No such file or directory: 'file.txt'

else 和 finally

try:
    print(num)
except:
    # 捕获到异常
    print("catch except")
else:
    # 没有发生异常会执行
    print('''don't find except''')
finally:
    # 始终会执行
    print('I must execute')

异常的传递

01.try嵌套

# 通过try嵌套有利于发现异常
try:
    try:
        print(num)
    finally:
        print('内部finally')
except Exception as e:
    print('catch inner except %s' % e)
# >内部finally
# catch inner except name 'num' is not defined

02.函数的嵌套调用

def fun1():
    print(num)


def func2():
    fun1()


try:
    func2()
except Exception as e:
    print('catch inner function except %s' % e)
# catch inner function except name 'num' is not defined
# 还可以在func2()或者func1()中捕获
# 在异常少的地方进行捕获,比较方便找到异常

抛出自定义异常

class AgeError(Exception):
    def __init__(self, age):
        self.age = age

    def __str__(self):
        return "{} AgeError age is illegal".format(self.age)


class Person(object):
    def __init__(self, name, age):
        if 1 < age < 150:
            self.name = name
            self.age = age
        else:
            raise AgeError(age)


xm = Person('yang', 222)
#    raise AgeError(age)
# __main__.AgeError: 222 AgeError age is illegal

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值