首頁 後端開發 Python教學 關於Python中異常(Exception)

關於Python中異常(Exception)

Apr 24, 2018 pm 04:14 PM
exception python 關於

這篇文章介紹的內容是關於Python中異常(Exception) ,有著一定的參考價值,現在分享給大家,有需要的朋友可以參考一下

異常是指程式中的例外,違例情況。異常機制是指程式出現錯誤後,程式的處理方法。當出現錯誤後,程式的執行流程改變,程式的控制權轉移到異常處理。以下這篇文章主要總結了關於Python中異常(Exception)的相關資料,需要的朋友可以參考下。

前言

Exception類是常用的異常類,該類別包括StandardError,StopIteration, GeneratorExit, Warning等異常類別。 python中的異常使用繼承結構創建,可以在異常處理程序中捕獲基類異常,也可以捕獲各種子類異常,python中使用try...except語句捕獲異常,異常子句定義在try子句後面。

Python中的例外處理

#異常處理的語句結構

try:
 <statements>  #运行try语句块,并试图捕获异常
except <name1>:
 <statements>  #如果name1异常发现,那么执行该语句块。
except (name2, name3):
 <statements>  #如果元组内的任意异常发生,那么捕获它
except <name4> as <variable>:
 <statements>  #如果name4异常发生,那么进入该语句块,并把异常实例命名为variable
except:
 <statements>  #发生了以上所有列出的异常之外的异常
else:
<statements>   #如果没有异常发生,那么执行该语句块
finally:
 <statement>   #无论是否有异常发生,均会执行该语句块。
登入後複製

說明

  • #else和finally是可選的,可能會有0個或多個except,但是,如果出現一個else的話,必須有至少一個except。

  • 不管你如何指定異常,異常總是透過實例物件來識別,並且大多數時候在任意給定的時刻啟動。一旦異常在程式中某處由一條except子句捕獲,它就死掉了,除非由另一個raise語句或錯誤重新引發它。

raise語句

raise語句用來手動拋出一個異常,有以下幾種呼叫格式:

  • raise #可以在raise語句之前建立該實例或在raise語句中建立。

  • raise #Python會隱式地建立類別的實例

  • #raise name(value) #拋出例外的同時,提供額外資訊value

  • raise # 把最近一次產生的例外重新拋出來

  • raise exception from E

例如:

拋出帶有額外資訊的ValueError: raise ValueError('we can only accept positive values')

當使用from的時候,第二個表達式指定了另一個異常類別或實例,它會附加到引發異常的__cause__屬性。如果引發的異常沒有捕獲,Python把異常也作為標準出錯訊息的一部分印出來:

#例如下面的程式碼:

##

try:
 1/0
except Exception as E:
 raise TypeError(&#39;bad input&#39;) from E
登入後複製

執行的結果如下:

Traceback (most recent call last):
 File "hh.py", line 2, in <module>
 1/0
ZeropisionError: pision by zero

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
 File "hh.py", line 4, in <module>
 raise TypeError(&#39;bad input&#39;) from E
TypeError: bad input
登入後複製

#assert語句

assert主要用來做斷言,通常用在單元測試中較多,到時候再做介紹。

with...as語句

with語句支援更豐富的基於物件的協議,可以為程式碼區塊定義支援進入和離開動作。


with語句對應的環境管理協定要求如下:

  • #環境管理器必須有

    __enter____exit__# #方法。

       __enter__方法會在初始化的時候運行,如果存在 ass子在,__enter__函數的回傳值會賦值給as子句中的變量,否則,直接丟棄。

       程式碼區塊中巢狀的程式碼會執行。

       如果with程式碼區塊引發異常, __exit__(type,value,traceback)方法就會被呼叫(有異常細節)。這些也是由 sys.exc_info傳回的相同值.如果此方法傳回值為假,則異常會重新引發。否則,異常會終止。正常 情況異常是應該被重新引發,這樣的話才能傳遞到with語句之外。

       如果with程式碼區塊沒有引發異常, __exit__方法依然會被調用,其type、value以及traceback參數都會以None傳遞。

下面是一個簡單的自訂的上下文管理類別。

class Block:
 def __enter__(self):
  print(&#39;entering to the block&#39;)
  return self
 
 def prt(self, args):
  print(&#39;this is the block we do %s&#39; % args)

 def __exit__(self,exc_type, exc_value, exc_tb):
  if exc_type is None:
   print(&#39;exit normally without exception&#39;)
  else:
   print(&#39;found exception: %s, and detailed info is %s&#39; % (exc_type, exc_value))
  return False

with Block() as b:
 b.prt(&#39;actual work!&#39;)
 raise ValueError(&#39;wrong&#39;)
登入後複製

如果登出上面的raise語句,那麼就會正常退出。

在沒有註銷掉該raise語句的情況下,運行結果如下:

#
entering to the block
this is the block we do actual work!
found exception: <class &#39;ValueError&#39;>, and detailed info is wrong
Traceback (most recent call last):
 File "hh.py", line 18, in <module>
 raise ValueError(&#39;wrong&#39;)
ValueError: wrong
登入後複製

##異常處理器

如果發生異常,那麼透過呼叫

sys.exc_info()函數,可以傳回包含3個元素的元組。第一個元素就是引發異常類,而第二個是實際引發的實例,第三個元素traceback對象,代表異常最初發生時所呼叫的堆疊。如果一切正常,那麼會回傳3個None。

Python的Builtins模組中定義的Exception

#

|Exception Name|Description|
|BaseException|Root class for all exceptions|
| SystemExit|Request termination of Python interpreter|
|KeyboardInterrupt|User interrupted execution (usually by pressing Ctrl+C)|
|Exception|Root class for regular exceptions|
| StopIteration|Iteration has no further values|
| GeneratorExit|Exception sent to generator to tell it to quit|
| SystemExit|Request termination of Python interpreter|
| StandardError|Base class for all standard built-in exceptions|
|  ArithmeticError|Base class for all numeric calculation errors|
|   FloatingPointError|Error in floating point calculation|
|   OverflowError|Calculation exceeded maximum limit for numerical type|
|   ZeropisionError|pision (or modulus) by zero error (all numeric types)|
|  AssertionError|Failure of assert statement|
|  AttributeError|No such object attribute|
|  EOFError|End-of-file marker reached without input from built-in|
|  EnvironmentError|Base class for operating system environment errors|
|   IOError|Failure of input/output operation|
|   OSError|Operating system error|
|    WindowsError|MS Windows system call failure|
|    ImportError|Failure to import module or object|
|    KeyboardInterrupt|User interrupted execution (usually by pressing Ctrl+C)|
|   LookupError|Base class for invalid data lookup errors|
|    IndexError|No such index in sequence|
|    KeyError|No such key in mapping|
|   MemoryError|Out-of-memory error (non-fatal to Python interpreter)|
|   NameError|Undeclared/uninitialized object(non-attribute)|
|    UnboundLocalError|Access of an uninitialized local variable|
|   ReferenceError|Weak reference tried to access a garbage collected object|
|   RuntimeError|Generic default error during execution|
|    NotImplementedError|Unimplemented method|
|   SyntaxError|Error in Python syntax|
|    IndentationError|Improper indentation|
|     TabErrorg|Improper mixture of TABs and spaces|
|   SystemError|Generic interpreter system error|
|   TypeError|Invalid operation for type|
|   ValueError|Invalid argument given|
|    UnicodeError|Unicode-related error|
|     UnicodeDecodeError|Unicode error during decoding|
|     UnicodeEncodeError|Unicode error during encoding|
|     UnicodeTranslate Error|Unicode error during translation|
|  Warning|Root class for all warnings|
|   DeprecationWarning|Warning about deprecated features|
|   FutureWarning|Warning about constructs that will change semantically in the future|
|   OverflowWarning|Old warning for auto-long upgrade|
|   PendingDeprecation Warning|Warning about features that will be deprecated in the future|
|   RuntimeWarning|Warning about dubious runtime behavior|
|   SyntaxWarning|Warning about dubious syntax|
|   UserWarning|Warning generated by user code|
登入後複製

相關推薦:


圖文詳解python異常處理方法

以上是關於Python中異常(Exception)的詳細內容。更多資訊請關注PHP中文網其他相關文章!

本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn

熱AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Clothoff.io

Clothoff.io

AI脫衣器

Video Face Swap

Video Face Swap

使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱工具

記事本++7.3.1

記事本++7.3.1

好用且免費的程式碼編輯器

SublimeText3漢化版

SublimeText3漢化版

中文版,非常好用

禪工作室 13.0.1

禪工作室 13.0.1

強大的PHP整合開發環境

Dreamweaver CS6

Dreamweaver CS6

視覺化網頁開發工具

SublimeText3 Mac版

SublimeText3 Mac版

神級程式碼編輯軟體(SublimeText3)

PHP和Python:解釋了不同的範例 PHP和Python:解釋了不同的範例 Apr 18, 2025 am 12:26 AM

PHP主要是過程式編程,但也支持面向對象編程(OOP);Python支持多種範式,包括OOP、函數式和過程式編程。 PHP適合web開發,Python適用於多種應用,如數據分析和機器學習。

在PHP和Python之間進行選擇:指南 在PHP和Python之間進行選擇:指南 Apr 18, 2025 am 12:24 AM

PHP適合網頁開發和快速原型開發,Python適用於數據科學和機器學習。 1.PHP用於動態網頁開發,語法簡單,適合快速開發。 2.Python語法簡潔,適用於多領域,庫生態系統強大。

PHP和Python:深入了解他們的歷史 PHP和Python:深入了解他們的歷史 Apr 18, 2025 am 12:25 AM

PHP起源於1994年,由RasmusLerdorf開發,最初用於跟踪網站訪問者,逐漸演變為服務器端腳本語言,廣泛應用於網頁開發。 Python由GuidovanRossum於1980年代末開發,1991年首次發布,強調代碼可讀性和簡潔性,適用於科學計算、數據分析等領域。

Python vs. JavaScript:學習曲線和易用性 Python vs. JavaScript:學習曲線和易用性 Apr 16, 2025 am 12:12 AM

Python更適合初學者,學習曲線平緩,語法簡潔;JavaScript適合前端開發,學習曲線較陡,語法靈活。 1.Python語法直觀,適用於數據科學和後端開發。 2.JavaScript靈活,廣泛用於前端和服務器端編程。

vs code 可以在 Windows 8 中運行嗎 vs code 可以在 Windows 8 中運行嗎 Apr 15, 2025 pm 07:24 PM

VS Code可以在Windows 8上運行,但體驗可能不佳。首先確保系統已更新到最新補丁,然後下載與系統架構匹配的VS Code安裝包,按照提示安裝。安裝後,注意某些擴展程序可能與Windows 8不兼容,需要尋找替代擴展或在虛擬機中使用更新的Windows系統。安裝必要的擴展,檢查是否正常工作。儘管VS Code在Windows 8上可行,但建議升級到更新的Windows系統以獲得更好的開發體驗和安全保障。

sublime怎麼運行代碼python sublime怎麼運行代碼python Apr 16, 2025 am 08:48 AM

在 Sublime Text 中運行 Python 代碼,需先安裝 Python 插件,再創建 .py 文件並編寫代碼,最後按 Ctrl B 運行代碼,輸出會在控制台中顯示。

visual studio code 可以用於 python 嗎 visual studio code 可以用於 python 嗎 Apr 15, 2025 pm 08:18 PM

VS Code 可用於編寫 Python,並提供許多功能,使其成為開發 Python 應用程序的理想工具。它允許用戶:安裝 Python 擴展,以獲得代碼補全、語法高亮和調試等功能。使用調試器逐步跟踪代碼,查找和修復錯誤。集成 Git,進行版本控制。使用代碼格式化工具,保持代碼一致性。使用 Linting 工具,提前發現潛在問題。

notepad 怎麼運行python notepad 怎麼運行python Apr 16, 2025 pm 07:33 PM

在 Notepad 中運行 Python 代碼需要安裝 Python 可執行文件和 NppExec 插件。安裝 Python 並為其添加 PATH 後,在 NppExec 插件中配置命令為“python”、參數為“{CURRENT_DIRECTORY}{FILE_NAME}”,即可在 Notepad 中通過快捷鍵“F6”運行 Python 代碼。

See all articles