Python3.6 异常处理和asser

2023-01-31 01:01:15 异常 python3 asser
# -----------------------
# __Author : tyran
# __Date : 17-11-13
# -----------------------

# 异常处理
try:
    # 代码逻辑,只要其中任意一行报错都会被捕捉
    i = int('aaa')
    print(i)
except Exception as e:  # 如果出错执行
    # 捕捉错误
    print(e)  # invalid literal for int() with base 10: 'aaa'
else:
    print('no Error')  # 当没有错误的时候才执行
finally:  # 不管出不出错一定会执行
    print('over')

# 这里的Exception是一个包容所有错误的类,当然也可以写一些分类
try:
    s = 'aaa'
    print(s[5])
except IndexError as e:
    print(e)  # string index out of range
except IOError as e:
    print(e)

# 这里也可以用另外一种写法
try:
    s = aaa
    print(s[5])
except (IndexError, NameError) as e:
    print(e)  # name 'aaa' is not defined

# 再来看主动触发异常
try:
    raise Exception('自首')
except Exception as e:
    print(e)  # 自首


# 自定义主动触发错误
class MyError(Exception):
    def __init__(self, msg):
        self.message = msg

    def __str__(self):
        return self.message


try:
    raise MyError('我错了')
except MyError as e:
    print(e)  # 我错了

# assert 断言
print(123)
assert 1 == 1  # assert 条件,满足就执行下去,不满足报错
print(456)

print(123)
assert False  # AssertionError
print(456)

相关文章