網站首頁 編程語言 正文
前言
相比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
相關推薦
- 2022-12-29 Python利用tkinter實現一個簡易番茄鐘的示例代碼_python
- 2021-12-06 C語言練習之數組中素數交換_C 語言
- 2022-12-23 Android入門之彈出式對話框的實現_Android
- 2022-07-22 python:實現abbreviation縮寫算法(附完整源碼)
- 2022-02-24 React插槽使用方法_React
- 2023-07-08 前端使用FileReader讀中文會亂碼
- 2022-12-07 R語言隨機抽樣詳解_R語言
- 2022-03-15 ...has been blocked by CORS policy: Response to pr
- 最近更新
-
- window11 系統安裝 yarn
- 超詳細win安裝深度學習環境2025年最新版(
- Linux 中運行的top命令 怎么退出?
- MySQL 中decimal 的用法? 存儲小
- get 、set 、toString 方法的使
- @Resource和 @Autowired注解
- Java基礎操作-- 運算符,流程控制 Flo
- 1. Int 和Integer 的區別,Jav
- spring @retryable不生效的一種
- Spring Security之認證信息的處理
- Spring Security之認證過濾器
- Spring Security概述快速入門
- Spring Security之配置體系
- 【SpringBoot】SpringCache
- Spring Security之基于方法配置權
- redisson分布式鎖中waittime的設
- maven:解決release錯誤:Artif
- restTemplate使用總結
- Spring Security之安全異常處理
- MybatisPlus優雅實現加密?
- Spring ioc容器與Bean的生命周期。
- 【探索SpringCloud】服務發現-Nac
- Spring Security之基于HttpR
- Redis 底層數據結構-簡單動態字符串(SD
- arthas操作spring被代理目標對象命令
- Spring中的單例模式應用詳解
- 聊聊消息隊列,發送消息的4種方式
- bootspring第三方資源配置管理
- GIT同步修改后的遠程分支