Python圈Python基础软件测试

Python5--异常处理

2020-08-24  本文已影响0人  伊洛的小屋
1.异常处理
# 伊洛Yiluo
# https://yiluotalk.com/
>>> file_path = '/usr/local/bin/error.py'
>>> f = open(file_path)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
FileNotFoundError: [Errno 2] No such file or directory: '/usr/local/bin/error.py'
2.Python 常用的异常类
3.异常处理方式
>>> file_path = '/usr/local/bin/error.py'
>>> try:
...     f = open(file_path)
... except FileNotFoundError as err:
...     print(err)
...
[Errno 2] No such file or directory: '/usr/local/bin/error.py'
>>> file_path = '/usr/local/bin/error.py'
>>> try:
...     f = open(file_path)
... except FileNotFoundError:
...     print('FileNotFoundError')
... finally:
...     print('Finally')
...
FileNotFoundError
Finally
4.抛出异常
raise ValueError()
5.Python 包管理工具
6.pip 的常见命令
7.错误和异常
8. 简单的例子
# 伊洛Yiluo
b = 1

c = a + b
print(c)

9. 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
10.多个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
11.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('结束异常')
# 伊洛Yiluo
# https://yiluotalk.com/
结束异常

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

欢迎下方【戳一下】【点赞】
Author:伊洛Yiluo
愿你享受每一天,Just Enjoy !

上一篇下一篇

猜你喜欢

热点阅读