Python3学习笔记——异常处理

#!/usr/bin/env python
# 1.异常处理

try:
	# 主要执行的代码 
except IndexError as e:
	# 对于某些错误需要特殊处理的,可以对特殊错误进行捕捉
	print('IndexError')
except Exception as e:  # 创建一个Exception的对象叫e,Exception中封装了错误代码信息
	# 上述代码出错,自动执行当前的代码块
	# Exception 包含了所有的错误
else:
	# 如果主要执行的代码没有错误,就执行else中的内容
finally:
	# 无论是否出现错误,最后都会执行的代码块
		
# 2.主动抛出异常
try:
	raise Exception('主动抛出的异常')
except Exception as e:
	print(e)

# 3.自定义异常
class myError(Exception):
	""" 自定义异常"""
	def __init__(self,msg):
		self.message = msg
	def __str__(self):
		return self.message
		
try:
	raise myError('自定义的异常')
except Exception as e:
	print(e)
	
# 4.断言 assert

	使用格式: assert 条件
	条件成立继续执行
	用于强制用户服从条件,否则报错,可以捕获,但一般不捕获

  

猜你喜欢

转载自www.cnblogs.com/rockley/p/9108524.html