python 编程开发 —— 异常处理(try-except-finally)

文档声明:
以下资料均属于本人在学习过程中产出的学习笔记,如果错误或者遗漏之处,请多多指正。并且该文档在后期会随着学习的深入不断补充完善。感谢各位的参考查看。


笔记资料仅供学习交流使用,转载请标明出处,谢谢配合。
如果存在相关知识点的遗漏,可以在评论区留言,看到后将在第一时间更新。
作者:Aliven888

1、简述

  我们在程序开发过程中总会遇到一些可以避免或者因为用户异常操作而不可避免的问题。当前对于前者可以避免的问题我们在程序开发和测试过程中会尽量去避免的。然后不可避免的就会变的很麻烦了。为了针对这种情况, python 引入了异常处理:程序出现逻辑错误或者因为用户输入非法导致的异常问题, 通过 python 提供的异常处理机制,在异常出现是,python 可以自动捕获异常,并且从内部消化掉。

1.1、AssertionError : 断言语句(assert)失败

  关键词 assert 后面的条件为假时,程序将停止并抛出异常 AssertionError 异常。

>>> string = 'aliven'
>>> assert len(string) > 0 # 不会抛出异常
>>> string = '' # 字符串置空
>>> assert len(string) > 0  # 抛出异常

Traceback (most recent call last):
  File "<pyshell#3>", line 1, in <module>
    assert len(string) > 0
AssertionError
>>> 

1.2、AttributeError :尝试访问未知的对象属性

  当试图访问的对象属性不存在时抛出异常。

>>> my_list = []
>>> my_list.aliven 

Traceback (most recent call last):
  File "<pyshell#5>", line 1, in <module>
    my_list.aliven
AttributeError: 'list' object has no attribute 'aliven'
>>> 

1.3、IndexError :索引超出序列的范围

  在使用序列的时候,经常会遇到 IndexError 异常, 原因就是索引超出序列范围。

>>> my_list = [1, 2, 3]
>>> my_list[3]

Traceback (most recent call last):
  File "<pyshell#7>", line 1, in <module>
    my_list[3]
IndexError: list index out of range

1.4、KeyError :字典中查找一个不存在的关键字

  当试图在字典中查找一个不存在的关键字的时候,就会引发 KeyError 异常,因此建议使用 dict.get() 方法。

>>> my_dict = {'one':1, 'two':2, 'three':3}
>>> my_dict['one']
1
>>> my_dict['four']

Traceback (most recent call last):
  File "<pyshell#10>", line 1, in <module>
    my_dict['four']
KeyError: 'four'
>>> 

1.5、NameError :尝试访问一个不存在的变量

  当尝试访问一个不存在的变量时,python 会抛出该异常。

>>> Aliven # 一个存在的变量

Traceback (most recent call last):
  File "<pyshell#11>", line 1, in <module>
    Aliven
NameError: name 'Aliven' is not defined

1.6、OSError :操作系统产生的异常

  OSError 顾名思义就是操作系统产生的异常,就像打开一个不存在的文件就会引发 FileNotFindError , 而 FileNotFindError 就是 OSError 的子类。

>>> f = open('E:\\a\\b.txt', 'r')

Traceback (most recent call last):
  File "<pyshell#16>", line 1, in <module>
    f = open('E:\\a\\b.txt', 'r')
IOError: [Errno 2] No such file or directory: 'E:\\a\\b.txt'
>>> 

1.7、SyntaxError :python 语法错误

  如果遇到 SyntaxError 是 python 的语法错误, 这时 python 的代码并不能继续执行,需要找到对应的错误并修改后才能正常执行代码。

>>> my_list = [1, 2, 3} # 括号左右不匹配
SyntaxError: invalid syntax
>>> 

1.8、TypeError :不同类型间的无效操作

  有些数据类型不同是不能进行计算的,否则就会抛出 TypeError 异常。

>>> 1 + '1'  # 整数 和 字符串 不能进行加法操作

Traceback (most recent call last):
  File "<pyshell#19>", line 1, in <module>
    1 + '1'
TypeError: unsupported operand type(s) for +: 'int' and 'str'

1.9、ZoreDivisionError 除数为 0

  在进行数据除法运算时, 除数是不能为 0 的。

>>> 4 / 0  # 除数为 0

Traceback (most recent call last):
  File "<pyshell#20>", line 1, in <module>
    4 / 0
ZeroDivisionError: integer division or modulo by zero

2、try-except 语句

  try-except :常用语检测和处理异常。
格式

try:
	检测范围
except [Exception1] [as reason]:  # 异常处理分支可以有多个
	出现异常后的处理代码1
except [Exception2] [as reason]:
	出现异常后的处理代码2
>>> try:
	5 / 0
except ZeroDivisionError as reason:
	print('zero ', str(reason))

	
('zero ', 'integer division or modulo by zero')
>>> 

3、try-except-finally 语句

  • 如果 try 语句中没有任何异常出现, 会跳过 except 语句执行 finally 语句。
  • 如果 try 语句出现异常,则会先执行 except 语句在执行 finally 语句。
  • finally 语句中的内容就是确保无论如何都会被执行的内容。

格式

try:
	检测范围
except [Exception1] [as reason]:  # 异常处理分支可以有多个
	出现异常后的处理代码1
except [Exception2] [as reason]:
	出现异常后的处理代码2
finally:
	finally语句体
# 读取不存在的文件
>>> try:
	f = open("F:\\Aliven\\a\\b.txt", 'w')
	print(f.read())
except IOError as reason:
	print('file not find')
finally:
	print('finally')
	f.close()

	
file not find  # 异常抛出
finally  # finally 语句

# 读取存在的文件
>>> try:
	f = open("D:\\Python\\P\\Aliven.txt", 'r')
	print(f.read())
except IOError as reason:
	print('file not find')
finally:
	print('finally')
	f.close()

	
Python test
hello world
good Python
finally
>>> 

4、try-except-else 语句

  try-except-else :else 语句将在 try 语句没有发生任何异常的时候执行。这里和 finally 是有区别的,else 是异常未发生时才会执行的。

格式

try:
	检测范围
except [Exception1] [as reason]:  # 异常处理分支可以有多个
	出现异常后的处理代码1
except [Exception2] [as reason]:
	出现异常后的处理代码2
else:
	else 语句体
# 异常发生时,不会执行 else
>>> try:
	f = open("F:\\Python\\P\\Aliven.txt", 'r')
	print(f.read())
except IOError as reason:
	print('file not find')
else:
	print('finally')
	f.close()

	
file not find
>>> 

# 异常未发生,执行 else
>>> try:
	f = open("D:\\Python\\P\\Aliven.txt", 'r')
	print(f.read())
except IOError as reason:
	print('file not find')
else:
	print('else')
	f.close()

	
Python test
hello world
good Python
else # else 语句输出

5、raise 语句

  raise :python 使用 raise 语句抛出一个指定的异常。

格式

raise [Exception [, args [, traceback]]]
>>> raise IOError

Traceback (most recent call last):
  File "<pyshell#61>", line 1, in <module>
    raise IOError
IOError
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值