前言
一、異常
1.1、忽略
1.2、捕獲
1.3、異常鏈
1.4、自定義
1.5、拋出
二、異常的顯示方式
2.1、打印信息
2.2、控制台警告
2.2、存儲文件
前言相比java,python的異常和java中不同,python主要是防止程序異常被中止。一旦被catch後它還行往下執行。
一、異常1.1、忽略pass這個關鍵字相當於一個占位符,好比TODO是一樣的,只表示此行什麼也不做,不代表其它的行代碼不執行;
try:print(5/0)except ZeroDivisionError:passprint("ddd") #這行還是可以正常執行的
1.2、捕獲def parse_int(s):try:n = int(v)except Exception as e:print('Could not parse, Reason:', e)parse_int('30') ##Reason: name 'v' is not defined
1.3、異常鏈try:client_obj.get_url(url)except (URLError, ValueError, SocketTimeout):client_obj.remove_url(url)
try:client_obj.get_url(url)except (URLError, ValueError):client_obj.remove_url(url)except SocketTimeout:client_obj.handle_url_timeout(url)
try:f = open(filename)except OSError:pass
1.4、自定義class NetworkError(Exception):passclass HostnameError(NetworkError):passclass CustomError(Exception):def __init__(self, message, status):super().__init__(message, status)self.message = messageself.status = status
try:msg = s.recv()except TimeoutError as e:print(e)except RuntimeError as e:print(e.args)
1.5、拋出try:raise RuntimeError('It failed') #拋出新異常-raise Errorexcept RuntimeError as e:print(e.args)
def example():try:int('N/A')except ValueError:print("Didn't work")raise #捕獲後再拋出
二、異常的顯示方式2.1、打印信息try:print(5/0)except ZeroDivisionError as e:print(e.args)
2.2、控制台警告import warningswarnings.simplefilter('always')def func(x, y, log_file=None, debug=False):if log_file is not None:warnings.warn('log_file argument deprecated', DeprecationWarning)func(1, 2, 'a')#第一行日志輸出warn內容,第二行輸出代碼內容/Users/liudong/personCode/python/pythonTest/app/base/base_type.py:5: UserWarning: log_file argument deprecatedwarnings.warn('log_file argument deprecated')
2.2、存儲文件import json;numbers = [2,3,4,5,6];fileName = "numbers.json";with open(fileName, "w") as fileObj:json.dump(numbers, fileObj);with open(fileName, "r") as fileObj:number1 = json.load(fileObj);
到此這篇關於Python包裝異常處理方法的文章就介紹到這了,更多相關Python 異常處理內容請搜索軟件開發網以前的文章或繼續浏覽下面的相關文章希望大家以後多多支持軟件開發網!