Python中的raise關(guān)鍵字詳解
更新時(shí)間:2025年04月14日 15:20:28 作者:Yant224
這篇文章主要介紹了Python中的raise關(guān)鍵字,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
一、核心語法解析
1.1 基礎(chǔ)語法形式
raise [異常類型[(參數(shù))]]
用法說明??:
- 只能存在于異常處理塊(
except
或finally
)內(nèi)部 - 自動(dòng)重新拋出當(dāng)前捕獲的異常
- 保持原始異常堆棧信息
1.2 完整語法結(jié)構(gòu)
raise [異常類型[(參數(shù))]] [from 原因]
二、基礎(chǔ)用法場景
2.1 觸發(fā)內(nèi)置異常
# 參數(shù)校驗(yàn)場景 def calculate_square(n): if not isinstance(n, (int, float)): raise TypeError("必須傳入數(shù)值類型") return n ?**? 2 # 調(diào)用示例 calculate_square("5") # 觸發(fā) TypeError
三、高級(jí)用法技巧
3.1 異常鏈(Exception Chaining)
import json try: config = json.load(open('config.json')) except FileNotFoundError as fnf_error: raise RuntimeError("配置文件加載失敗") from fnf_error # 錯(cuò)誤輸出顯示關(guān)聯(lián)關(guān)系 # RuntimeError: 配置文件加載失敗 # The above exception was the direct cause of...
3.2 自定義異常觸發(fā)python
class NetworkTimeout(Exception): """自定義網(wǎng)絡(luò)超時(shí)異常""" def __init__(self, host, timeout): self.host = host self.timeout = timeout super().__init__(f"連接 {host} 超時(shí)({timeout}s)") # 觸發(fā)自定義異常 if response_time > 30: raise NetworkTimeout("api.example.com", 30)
四、特殊形式詳解
4.1 無異常類型拋出
def deprecated_feature(): raise "該功能已廢棄" # ? 錯(cuò)誤!必須拋出 Exception 實(shí)例 # 正確做法 def deprecated_feature(): raise DeprecationWarning("該功能已廢棄")
4.2 異常參數(shù)傳遞
try: raise ValueError("無效輸入", 404, {"detail": "ID不合法"}) except ValueError as e: print(e.args) # ('無效輸入', 404, {'detail': 'ID不合法'})
五、常見使用模式
5.1 防御式編程
def divide(a, b): if b == 0: raise ZeroDivisionError("除數(shù)不能為零") return a / b
5.2 API 錯(cuò)誤處理
def fetch_data(url): response = requests.get(url) if 400 <= response.status_code < 500: raise ClientError(response.status_code, response.text) elif response.status_code >= 500: raise ServerError(response.status_code) return response.json()
六、最佳實(shí)踐指南
6.1 異常類型選擇原則
錯(cuò)誤場景 | 推薦異常類型 |
---|---|
參數(shù)類型錯(cuò)誤 | TypeError |
參數(shù)值無效 | ValueError |
文件操作錯(cuò)誤 | IOError |
業(yè)務(wù)規(guī)則違反 | 自定義異常 |
6.2 異常消息規(guī)范
# 不推薦 raise ValueError("錯(cuò)誤發(fā)生") # 推薦格式 raise ValueError(f"參數(shù) {param} 的值 {value} 超出有效范圍(允許范圍:{min}~{max})")
七、注意事項(xiàng)
from
參數(shù)使用??
# 顯示原始異常原因 raise ParsingError from original_error
性能考量??
- 避免在循環(huán)中頻繁拋出異常
- 異常處理耗時(shí)是條件判斷的
10-100
倍
調(diào)試輔助??
# 打印完整堆棧 import traceback try: risky_call() except: traceback.print_exc() raise # 重新拋出
八、綜合應(yīng)用示例
8.1 數(shù)據(jù)驗(yàn)證鏈
def validate_user(user): if not user.get('username'): raise ValueError("用戶名必填") if len(user['password']) < 8: raise SecurityError("密碼至少8位") if not re.match(r"[^@]+@[^@]+\.[^@]+", user['email']): raise FormatError("郵箱格式無效") return True
8.2 上下文管理器
class Transaction: def __enter__(self): if not self.conn.is_valid(): raise ConnectionError("數(shù)據(jù)庫連接失效") return self def __exit__(self, exc_type, exc_val, exc_tb): if exc_type: self.rollback() raise TransactionError("事務(wù)執(zhí)行失敗") from exc_val self.commit()
總結(jié)
以上為個(gè)人經(jīng)驗(yàn),希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。
相關(guān)文章
Python3實(shí)現(xiàn)生成隨機(jī)密碼的方法
這篇文章主要介紹了Python3實(shí)現(xiàn)生成隨機(jī)密碼的方法,是Python程序設(shè)計(jì)中非常實(shí)用的一個(gè)技巧,需要的朋友可以參考下2014-08-08Python3 jupyter notebook 服務(wù)器搭建過程
這篇文章主要介紹了Python3 jupyter notebook 服務(wù)器搭建過程,非常不錯(cuò),具有一定的參考借鑒價(jià)值,需要的朋友參考下吧2018-11-11一文了解python 3 字符串格式化 F-string 用法
本文介紹在python 3 編程中,如何進(jìn)行字符串格式化。介紹了F-string的用法,通過實(shí)例代碼給大家介紹的非常詳細(xì),對(duì)大家的工作或?qū)W習(xí)具有一定的參考借鑒價(jià)值,需要的朋友參考下吧2020-03-03基于Python pyecharts實(shí)現(xiàn)多種圖例代碼解析
這篇文章主要介紹了基于Python pyecharts實(shí)現(xiàn)多種圖例代碼解析,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2020-08-08在Python中使用sort()方法進(jìn)行排序的簡單教程
這篇文章主要介紹了在Python中使用sort()方法進(jìn)行排序的簡單教程,是Python學(xué)習(xí)中的基礎(chǔ)知識(shí),需要的朋友可以參考下2015-05-05