python異常大總結
python用異常物件(exception object)來表示異常狀況。遇到錯誤後,會引發異常。如果異常物件並未被處理或捕捉,程式就會用所謂的回溯(Traceback, 一種錯誤訊息)終止執行:
>>> 1/0
Traceback (most recent call last):
File "
1/0
ZeroDivisionError: integer division or modulo by zero
raise 語句
為了引發異常,可以使用一個類別來引發例外語句。以下的範例使用內建的Exception異常類別:
>>> raise Exception #引发一个没有任何错误信息的普通异常 Traceback (most recent call last): File "<pyshell#1>", line 1, in <module> raise Exception Exception >>> raise Exception('hyperdrive overload') # 添加了一些异常错误信息 Traceback (most recent call last): File "<pyshell#2>", line 1, in <module> raise Exception('hyperdrive overload') Exception: hyperdrive overload
系統自帶的內建異常類別:
>>> import exceptions
>> dir(exceptor> 'AssertionError', 'AttributeError', 'BaseException', 'BufferError', 'BytesWarning', 'DeprecationWarning', 'EOFError', 'EnvironmentError', 'Exception', 'FloatingPoint,'Error', 'EnvironmentError', 'Exception', 'FloatingPoint,'Error', 'Gentures'Fluninga'IO, 'Error'IO, 'Gen ', 'ImportError', 'ImportWarning', 'IndentationError', 'IndexError', 'KeyError', 'KeyboardInterrupt', 'LookupError', 'MemoryError', 'NameError', 'NotImplementedError', 'MemoryError', 'NameError', 'NotImplementedError', 'Error' 'PendingDeprecationWarning', 'ReferenceError', 'RuntimeError', 'RuntimeWarning', 'StandardError', 'StopIteration', 'SyntaxError', 'SyntaxWarning', 'SystemError', 'Systemup ', 'UnicodeDecodeError', 'UnicodeEncodeError', 'UnicodeError', 'UnicodeTranslateError', 'UnicodeWarning', 'UserWarning', 'ValueError', 'Warning', 'WindowsError', 'ZerovisionError', 'name__,', ' '__package__']
哇!好多,常用的內建異常類別:
自訂異常
儘管內建的異常類別已經包括了大部分的情況,而且對於許多要求都已經足夠了,但有些時候還是需要創建自己的異常類別。
和常見其它類別一樣----只是要確保從Exception類別繼承,不管直接繼承還是間接繼承。像下面這樣:
>>> class someCustomExcetion(Exception):pass
當然,也可以為這個類別加入一些方法。
捕捉異常
我們可以使用 try/except 來實現異常的捕捉處理。
假設建立了一個讓使用者輸入兩個數,然後進行相除的程序:
x = input('Enter the first number: ') y = input('Enter the second number: ') print x/y #运行并且输入 Enter the first number: 10 Enter the second number: 0 Traceback (most recent call last): File "I:/Python27/yichang", line 3, in <module> print x/y ZeroDivisionError: integer division or modulo by zero 为了捕捉异常并做出一些错误处理,可以这样写: try: x = input('Enter the first number: ') y = input('Enter the second number: ') print x/y except ZeroDivisionError: print "输入的数字不能为0!" #再来运行 >>> Enter the first number: 10 Enter the second number: 0
輸入的數字不能為0! #怎麼樣?這次已經友善的多了
假如,我們在調試的時候引發異常會好些,如果在與用戶的進行交互的過程中又是不希望用戶看到異常信息的。那如何開啟/關閉 “屏蔽”機制?
class MuffledCalulator: muffled = False #这里默认关闭屏蔽 def calc(self,expr): try: return eval(expr) except ZeroDivisionError: if self.muffled: print 'Divsion by zero is illagal' else: raise #运行程序: >>> calculator = MuffledCalulator() >>> calculator.calc('10/2') 5 >>> calculator.clac('10/0') Traceback (most recent call last): File "<pyshell#30>", line 1, in <module> calculator.clac('10/0') AttributeError: MuffledCalulator instance has no attribute 'clac' #异常信息被输出了 >>> calculator.muffled = True #现在打开屏蔽 >>> calculator.calc('10/0') Divsion by zero is illagal
多個except 子句
如果執行上面的(輸入兩個數,求除法)程序,輸入面的內容,就會產生另一個異常:
好吧!我們可以再加個異常的處理來處理這個情況:try: x = input('Enter the first number: ') y = input('Enter the second number: ') print x/y except ZeroDivisionError: print "输入的数字不能为0!" #运行输入: >>> Enter the first number: 10 Enter the second number: 'hello.word' #输入非数字 Traceback (most recent call last): File "I:\Python27\yichang", line 4, in <module> print x/y TypeError: unsupported operand type(s) for /: 'int' and 'str' #又报出了别的异常信息
try: x = input('Enter the first number: ') y = input('Enter the second number: ') print x/y except ZeroDivisionError: print "输入的数字不能为0!" except TypeError: # 对字符的异常处理 print "请输入数字!" #再来运行: >>> Enter the first number: 10 Enter the second number: 'hello,word'
就算全部異常了的程序,運行之後,假如我輸入了下面的內容呢
try: x = input('Enter the first number: ') y = input('Enter the second number: ') print x/y except (ZeroDivisionError,TypeError,NameError): print "你的数字不对!
>>> Enter the first number: 10 Enter the second number: #不输入任何内容,回车 Traceback (most recent call last): File "I:\Python27\yichang", line 3, in <module> y = input('Enter the second number: ') File "<string>", line 0 ^ SyntaxError: unexpected EOF while parsing

熱AI工具

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

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

Undress AI Tool
免費脫衣圖片

Clothoff.io
AI脫衣器

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

熱門文章

熱工具

記事本++7.3.1
好用且免費的程式碼編輯器

SublimeText3漢化版
中文版,非常好用

禪工作室 13.0.1
強大的PHP整合開發環境

Dreamweaver CS6
視覺化網頁開發工具

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

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

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

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

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

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

在 Visual Studio Code(VSCode)中編寫代碼簡單易行,只需安裝 VSCode、創建項目、選擇語言、創建文件、編寫代碼、保存並運行即可。 VSCode 的優點包括跨平台、免費開源、強大功能、擴展豐富,以及輕量快速。

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

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