
- Python 基礎
- Python - 首頁
- Python - 概述
- Python - 歷史
- Python - 特性
- Python vs C++
- Python - Hello World 程式
- Python - 應用領域
- Python - 直譯器
- Python - 環境搭建
- Python - 虛擬環境
- Python - 基本語法
- Python - 變數
- Python - 資料型別
- Python - 型別轉換
- Python - Unicode 系統
- Python - 字面量
- Python - 運算子
- Python - 算術運算子
- Python - 比較運算子
- Python - 賦值運算子
- Python - 邏輯運算子
- Python - 位運算子
- Python - 成員運算子
- Python - 身份運算子
- Python - 運算子優先順序
- Python - 註釋
- Python - 使用者輸入
- Python - 數字
- Python - 布林值
- Python 控制語句
- Python - 控制流
- Python - 決策
- Python - If 語句
- Python - If else
- Python - 巢狀 If
- Python - Match-Case 語句
- Python - 迴圈
- Python - for 迴圈
- Python - for-else 迴圈
- Python - While 迴圈
- Python - break 語句
- Python - continue 語句
- Python - pass 語句
- Python - 巢狀迴圈
- Python 函式 & 模組
- Python - 函式
- Python - 預設引數
- Python - 關鍵字引數
- Python - 僅限關鍵字引數
- Python - 位置引數
- Python - 僅限位置引數
- Python - 可變引數
- Python - 變數作用域
- Python - 函式註解
- Python - 模組
- Python - 內建函式
- Python 字串
- Python - 字串
- Python - 字串切片
- Python - 修改字串
- Python - 字串連線
- Python - 字串格式化
- Python - 跳脫字元
- Python - 字串方法
- Python - 字串練習
- Python 列表
- Python - 列表
- Python - 訪問列表元素
- Python - 修改列表元素
- Python - 新增列表元素
- Python - 刪除列表元素
- Python - 遍歷列表
- Python - 列表推導式
- Python - 排序列表
- Python - 複製列表
- Python - 合併列表
- Python - 列表方法
- Python - 列表練習
- Python 元組
- Python - 元組
- Python - 訪問元組元素
- Python - 更新元組
- Python - 解包元組
- Python - 遍歷元組
- Python - 合併元組
- Python - 元組方法
- Python - 元組練習
- Python 集合
- Python - 集合
- Python - 訪問集合元素
- Python - 新增集合元素
- Python - 刪除集合元素
- Python - 遍歷集合
- Python - 合併集合
- Python - 複製集合
- Python - 集合運算子
- Python - 集合方法
- Python - 集合練習
- Python 字典
- Python - 字典
- Python - 訪問字典元素
- Python - 修改字典元素
- Python - 新增字典元素
- Python - 刪除字典元素
- Python - 字典檢視物件
- Python - 遍歷字典
- Python - 複製字典
- Python - 巢狀字典
- Python - 字典方法
- Python - 字典練習
- Python 陣列
- Python - 陣列
- Python - 訪問陣列元素
- Python - 新增陣列元素
- Python - 刪除陣列元素
- Python - 遍歷陣列
- Python - 複製陣列
- Python - 反轉陣列
- Python - 排序陣列
- Python - 合併陣列
- Python - 陣列方法
- Python - 陣列練習
- Python 檔案處理
- Python - 檔案處理
- Python - 寫入檔案
- Python - 讀取檔案
- Python - 重新命名和刪除檔案
- Python - 目錄
- Python - 檔案方法
- Python - OS 檔案/目錄方法
- Python - OS 路徑方法
- 面向物件程式設計
- Python - OOPs 概念
- Python - 類 & 物件
- Python - 類屬性
- Python - 類方法
- Python - 靜態方法
- Python - 建構函式
- Python - 訪問修飾符
- Python - 繼承
- Python - 多型
- Python - 方法重寫
- Python - 方法過載
- Python - 動態繫結
- Python - 動態型別
- Python - 抽象
- Python - 封裝
- Python - 介面
- Python - 包
- Python - 內部類
- Python - 匿名類和物件
- Python - 單例類
- Python - 包裝類
- Python - 列舉
- Python - 反射
- Python 錯誤 & 異常
- Python - 語法錯誤
- Python - 異常
- Python - try-except 塊
- Python - try-finally 塊
- Python - 丟擲異常
- Python - 異常鏈
- Python - 巢狀 try 塊
- Python - 使用者自定義異常
- Python - 日誌記錄
- Python - 斷言
- Python 內建異常
- Python 多執行緒
- Python - 多執行緒
- Python - 執行緒生命週期
- Python - 建立執行緒
- Python - 啟動執行緒
- Python - 加入執行緒
- Python - 執行緒命名
- Python - 執行緒排程
- Python - 執行緒池
- Python - 主執行緒
- Python - 執行緒優先順序
- Python - 守護執行緒
- Python - 執行緒同步
- Python 同步
- Python - 執行緒間通訊
- Python - 執行緒死鎖
- Python - 中斷執行緒
- Python 網路程式設計
- Python - 網路程式設計
- Python - 套接字程式設計
- Python - URL 處理
- Python - 泛型
- Python 庫
- NumPy 教程
- Pandas 教程
- SciPy 教程
- Matplotlib 教程
- Django 教程
- OpenCV 教程
- Python 雜項
- Python - 日期 & 時間
- Python - 數學
- Python - 迭代器
- Python - 生成器
- Python - 閉包
- Python - 裝飾器
- Python - 遞迴
- Python - 正則表示式
- Python - PIP
- Python - 資料庫訪問
- Python - 弱引用
- Python - 序列化
- Python - 模板
- Python - 輸出格式化
- Python - 效能測量
- Python - 資料壓縮
- Python - CGI 程式設計
- Python - XML 處理
- Python - GUI 程式設計
- Python - 命令列引數
- Python - 文件字串
- Python - JSON
- Python - 傳送郵件
- Python - 擴充套件
- Python - 工具/實用程式
- Python - GUI
- Python 高階概念
- Python - 抽象基類
- Python - 自定義異常
- Python - 高階函式
- Python - 物件內部
- Python - 記憶體管理
- Python - 元類
- Python - 使用元類進行超程式設計
- Python - 模擬和存根
- Python - 猴子補丁
- Python - 訊號處理
- Python - 型別提示
- Python - 自動化教程
- Python - Humanize 包
- Python - 上下文管理器
- Python - 協程
- Python - 描述符
- Python - 診斷和修復記憶體洩漏
- Python - 不可變資料結構
- Python 有用資源
- Python - 問答
- Python - 線上測驗
- Python - 快速指南
- Python - 參考
- Python - 速查表
- Python - 專案
- Python - 有用資源
- Python - 討論
- Python 編譯器
- NumPy 編譯器
- Matplotlib 編譯器
- SciPy 編譯器
Python 內建異常
內建異常是 Python 中預定義的錯誤類,用於處理程式中的錯誤和異常情況。它們派生自基類“BaseException”,並且是標準庫的一部分。
Python 中標準內建異常
以下是 Python 中可用的標準異常列表 -
序號 | 異常名稱 & 描述 |
---|---|
1 | 異常 所有異常的基類 |
2 | StopIteration 當迭代器的 next() 方法不指向任何物件時引發。 |
3 | SystemExit 由 sys.exit() 函式引發。 |
4 | StandardError 除 StopIteration 和 SystemExit 之外,所有內建異常的基類。 |
5 | ArithmeticError 所有發生在數值計算中的錯誤的基類。 |
6 | OverflowError 當計算超出數值型別的最大限制時引發。 |
7 | FloatingPointError 當浮點計算失敗時引發。 |
8 | ZeroDivisonError 當對所有數值型別進行除法或取模運算時除數為零時引發。 |
9 | AssertionError 在 Assert 語句失敗的情況下引發。 |
10 | AttributeError 在屬性引用或賦值失敗的情況下引發。 |
11 | EOFError 當 raw_input() 或 input() 函式沒有輸入並且到達檔案末尾時引發。 |
12 | ImportError 當 import 語句失敗時引發。 |
13 | KeyboardInterrupt 當用戶中斷程式執行時引發,通常是透過按下 Ctrl+C。 |
14 | LookupError 所有查詢錯誤的基類。 |
15 | IndexError 當在序列中找不到索引時引發。 |
16 | KeyError 當在字典中找不到指定的鍵時引發。 |
17 | NameError 當在本地或全域性名稱空間中找不到識別符號時引發。 |
18 | UnboundLocalError 當嘗試訪問函式或方法中的區域性變數但未為其賦值時引發。 |
19 | EnvironmentError 發生在 Python 環境之外的所有異常的基類。 |
20 | IOError 當輸入/輸出操作失敗時引發,例如 print 語句或 open() 函式在嘗試開啟不存在的檔案時。 |
21 | OSError 針對與作業系統相關的錯誤引發。 |
22 | SyntaxError 當 Python 語法中存在錯誤時引發。 |
23 | IndentationError 當縮排未正確指定時引發。 |
24 | SystemError 當直譯器發現內部問題時引發,但是當遇到此錯誤時,Python 直譯器不會退出。 |
25 | SystemExit 當 Python 直譯器使用 sys.exit() 函式退出時引發。如果程式碼中未處理,會導致直譯器退出。 |
26 | TypeError 當嘗試對指定資料型別無效的操作或函式時引發。 |
27 | ValueError 當資料型別的內建函式具有有效的引數型別,但引數具有指定的無效值時引發。 |
28 | RuntimeError 當生成的錯誤不屬於任何類別時引發。 |
29 | NotImplementedError 當需要在繼承類中實現的抽象方法實際上未實現時引發。 |
以下是一些標準異常的示例 -
IndexError
當嘗試訪問無效索引處的專案時顯示。
numbers=[10,20,30,40] for n in range(5): print (numbers[n])
將產生以下輸出 -
10 20 30 40 Traceback (most recent call last): print (numbers[n]) IndexError: list index out of range
模組未找到錯誤
當無法找到模組時顯示此錯誤。
import notamodule Traceback (most recent call last): import notamodule ModuleNotFoundError: No module named 'notamodule'
KeyError
它發生在字典鍵未找到時。
D1={'1':"aa", '2':"bb", '3':"cc"} print ( D1['4']) Traceback (most recent call last): D1['4'] KeyError: '4'
ImportError
當指定的函式不可匯入時顯示此錯誤。
from math import cube Traceback (most recent call last): from math import cube ImportError: cannot import name 'cube'
StopIteration
當迭代器流耗盡後呼叫 next() 函式時,會出現此錯誤。
.it=iter([1,2,3]) next(it) next(it) next(it) next(it) Traceback (most recent call last): next(it) StopIteration
TypeError
當運算子或函式應用於不合適的物件型別時顯示此錯誤。
print ('2'+2) Traceback (most recent call last): '2'+2 TypeError: must be str, not int
ValueError
當函式的引數型別不合適時顯示此錯誤。
print (int('xyz')) Traceback (most recent call last): int('xyz') ValueError: invalid literal for int() with base 10: 'xyz'
NameError
當無法找到物件時遇到此錯誤。
print (age) Traceback (most recent call last): age NameError: name 'age' is not defined
零除錯誤
當除法中的第二個運算數為零時顯示此錯誤。
x=100/0 Traceback (most recent call last): x=100/0 ZeroDivisionError: division by zero
KeyboardInterrupt
當用戶在程式執行過程中按下中斷鍵(通常是 Control-C)時。
name=input('enter your name') enter your name^c Traceback (most recent call last): name=input('enter your name') KeyboardInterrupt
內建異常的層次結構
Python 中的異常以層次結構組織,頂部是“BaseException”。以下是一個簡化的層次結構:
- BaseException
- SystemExit
- KeyboardInterrupt
- 異常
- ArithmeticError
- FloatingPointError
- OverflowError
- 零除錯誤
- AttributeError
- EOFError
- ImportError
- LookupError
- IndexError
- KeyError
- MemoryError
- NameError
- UnboundLocalError
- OSError
- FileNotFoundError
- TypeError
- ValueError
- ---(還有許多其他異常)---
- ArithmeticError
如何使用內建異常
我們已經知道 Python 中的內建異常是預定義的類,用於處理特定的錯誤條件。現在,以下是如何在 Python 程式中有效使用它們的詳細指南:
使用 try-except 塊處理異常
在 Python 中處理異常的主要方法是使用“try-except”塊。這允許您捕獲並響應程式碼執行期間可能發生的異常。
示例
在以下示例中,可能引發異常的程式碼放置在“try”塊中。“except”塊捕獲指定的異常“ZeroDivisionError”並進行處理。
try: result = 1 / 0 except ZeroDivisionError as e: print(f"Caught an exception: {e}")
以下是獲得的輸出:
Caught an exception: division by zero
處理多個異常
您可以透過在“except”塊中以元組的形式指定多個異常來處理多個異常,如下面的示例所示:
try: result = int('abc') except (ValueError, TypeError) as e: print(f"Caught a ValueError or TypeError: {e}")
以上程式碼的輸出如下所示:
Caught a ValueError or TypeError: invalid literal for int() with base 10: 'abc'
使用“else”和“finally”塊
如果“try”子句中的程式碼塊沒有引發異常,則執行“else”塊:
try: number = int(input("Enter a number: ")) except ValueError as e: print(f"Invalid input: {e}") else: print(f"You entered: {number}")
以上程式碼的輸出根據給定的輸入而有所不同:
Enter a number: bn Invalid input: invalid literal for int() with base 10: 'bn'
無論是否發生異常,“finally”塊都會始終執行。它通常用於清理操作,例如關閉檔案或釋放資源:
try: file = open('example.txt', 'r') content = file.read() except FileNotFoundError as e: print(f"File not found: {e}") finally: file.close() print("File closed.")
以下是以上程式碼的輸出:
File closed.
顯式引發內建異常
在 Python 中,您可以引發內建異常來指示程式碼中的錯誤或異常情況。這允許您處理特定的錯誤場景,並向用戶或除錯應用程式的開發人員提供資訊豐富的錯誤訊息。
語法
以下是引發內建異常的基本語法:
raise ExceptionClassName("Error message")
示例
在此示例中,“divide”函式嘗試除兩個數字“a”和“b”。如果“b”為零,則會引發“ZeroDivisionError”並顯示自定義訊息:
def divide(a, b): if b == 0: raise ZeroDivisionError("Cannot divide by zero") return a / b try: result = divide(10, 0) except ZeroDivisionError as e: print(f"Error: {e}")
獲得的輸出如下所示:
Error: Cannot divide by zero