日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學無先后,達者為師

網站首頁 編程語言 正文

Python包裝異常處理方法_python

作者:生而為人我很遺憾 ? 更新時間: 2022-08-15 編程語言

前言

相比java,python的異常和java中不同,python主要是防止程序異常被中止。一旦被catch后它還行往下執行。

一、異常

1.1、忽略

pass這個關鍵字相當于一個占位符,好比TODO是一樣的,只表示此行什么也不做,不代表其它的行代碼不執行;

try:
print(5/0)
except ZeroDivisionError:
pass
print("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):
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內容,第二行輸出代碼內容
/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);

原文鏈接:https://blog.51cto.com/arch/5397837

欄目分類
最近更新