1. 程式人生 > >Python3學習筆記——異常處理

Python3學習筆記——異常處理

創建 n) 執行 sse usr true 異常處理 exce __str__

#!/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 條件
	條件成立繼續執行
	用於強制用戶服從條件,否則報錯,可以捕獲,但一般不捕獲

  

Python3學習筆記——異常處理