Python包裝異常處理方法
前言
相比java,python的異常和java中不同,python主要是防止程序異常被中止。一旦被catch后它還行往下執(zhí)行。
一、異常
1.1、忽略
pass這個關(guān)鍵字相當(dāng)于一個占位符,好比TODO是一樣的,只表示此行什么也不做,不代表其它的行代碼不執(zhí)行;
try:
print(5/0)
except ZeroDivisionError:
pass
print("ddd") #這行還是可以正常執(zhí)行的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 defined1.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): pass class HostnameError(NetworkError): pass class CustomError(Exception): def __init__(self, message, status): super().__init__(message, status) self.message = message self.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 Error
except 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 warnings
warnings.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內(nèi)容,第二行輸出代碼內(nèi)容
/Users/liudong/personCode/python/pythonTest/app/base/base_type.py:5: UserWarning: log_file argument deprecated
warnings.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);
到此這篇關(guān)于Python包裝異常處理方法的文章就介紹到這了,更多相關(guān)Python 異常處理內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
python-圖片流傳輸?shù)乃悸芳笆纠?url轉(zhuǎn)換二維碼)
這篇文章主要介紹了python-圖片流傳輸?shù)乃悸芳笆纠?url轉(zhuǎn)換二維碼),幫助大家更好的理解和使用python,感興趣的朋友可以了解下2020-12-12
python3?字符串str和bytes相互轉(zhuǎn)換
這篇文章主要介紹了python3?字符串str和bytes相互轉(zhuǎn)換,在文件傳輸過程中,通常使用bytes格式的數(shù)據(jù)流,而代碼中通常用str類型,因此str和bytes的相互轉(zhuǎn)換就尤為重要,下文詳細(xì)介紹需要的小伙伴可以參考一下2022-03-03
Pandas實(shí)現(xiàn)數(shù)據(jù)拼接的操作方法詳解
Python處理大規(guī)模數(shù)據(jù)集的時候經(jīng)常需要使用到合并、鏈接的方式進(jìn)行數(shù)據(jù)集的整合,本文為大家主要介紹了.merge()、?.join()?和?.concat()?三種方法,感興趣的可以了解一下2022-04-04
mac下給python3安裝requests庫和scrapy庫的實(shí)例
今天小編就為大家分享一篇mac下給python3安裝requests庫和scrapy庫的實(shí)例,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2018-06-06
詳解Python中Pandas read_csv參數(shù)使用
在使用 Pandas 進(jìn)行數(shù)據(jù)分析和處理時,read_csv 是一個非常常用的函數(shù),本文將詳細(xì)介紹 read_csv 函數(shù)的各個參數(shù)及其用法,希望對大家有所幫助2022-10-10
python利用wx實(shí)現(xiàn)界面按鈕和按鈕監(jiān)聽和字體改變的方法
今天小編就為大家分享一篇python利用wx實(shí)現(xiàn)界面按鈕和按鈕監(jiān)聽和字體改變的方法,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2019-07-07

