软件测试测试员的那点事Ulord社区联盟

Python基础 Zero to Hero 异常的处理 (一)

2019-12-16  本文已影响0人  伊洛的小屋
1. 异常的定义
2. 错误和异常
3. 简单的例子
# 伊洛Yiluo
b = 1

c = a + b
print(c)

3. try, except 的使用
# 伊洛Yiluo
b = 1
try:
    c = a + b
    print(c)
except NameError as err:
    print('错误:{}'.format(err))

错误:name 'a' is not defined

Process finished with exit code 0
4.多个except
# 伊洛Yiluo
a = 2
b = 1

try:
    c = a + b
    print(c)
    f = open('/yiluo/bin/activate.txt')

except NameError as err:
    print('错误:{}'.format(err))

except FileNotFoundError as err2:
    print('错误:{}'.format(err2))

3
错误:[Errno 2] No such file or directory: '/yiluo/bin/activate.txt'

Process finished with exit code 0
# 伊洛Yiluo
b = 1

try:
    c = a + b
    f = open('/yiluo/bin/activate.txt')

except:
    print('总之就是有错误')
总之就是有错误

Process finished with exit code 0
5.finally的使用
# 伊洛Yiluo
a = 2
b = 1

try:
    c = a + b
    f = open('/yiluo/bin/activate.txt')

except:
    print('总之就是有错误')

finally:
    print('结束异常')

总之就是有错误
结束异常

Process finished with exit code 0
# 伊洛Yiluo
a = 2
b = 1

try:
    c = a + b
except:
    print('总之就是有错误')

finally:
    print('结束异常')
结束异常

Process finished with exit code 0
6.抛出异常
>>> raise NameError('Error ERROR')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: Error ERROR
......待续

欢迎下方【戳一下】【点赞】
Author:伊洛Yiluo
2019年12月16日
愿您享受每一天,Just Enjoy !

上一篇 下一篇

猜你喜欢

热点阅读