Python錯誤與例外概念(總)
1.錯誤與例外的處理方式
常見的錯誤
a:NameError
if True:SyntaxError
f = oepn('1.txt'):IOError
10/0:ZeropisionError
a = int('d'):ValueError
#程式運作中斷:KeyboardInterrupt
2.Python-使用try_except處理例外(1)
try: try_suite except Exception [e]: exception_block
try用來捕捉try_suite中的錯誤,並且將錯誤交給except處理
except用來處理異常,如果處理異常和設定捕獲異常一致,使用exception_block處理異常
# case 1 try: undef except: print 'catch an except'
# case 2 try: if undef except: print 'catch an except'
case1:可以捕獲異常,因為是運行時錯誤
case2:不能捕獲異常,因為是語法錯誤,運行前錯誤
--
# case 3 try: undef except NameError,e: print 'catch an except',e
# case 4 try: undef except IOError,e: print 'catch an except',e
- ##case3:可以捕獲異常,因為設定捕獲NameError異常 ##case4:不能捕獲異常,因為設定IOError,不會處理NameError
- Example
import random num = random.randint(0, 100) while True: try: guess = int(raw_input("Enter 1~100")) except ValueError, e: print "Enter 1~100" continue if guess > num: print "guess Bigger:", guess elif guess < num: print "guess Smaller:", guess elif guess == num: print "Guess OK,Game Over" break print '\n'
3. Python使用try_except處理例外(2)
- #try -except:處理多個異常
-
try: try_suite except Exception1[e]: exception_block1 except Exception2[e]: exception_block2 except ExceptionN[e]: exception_blockN
4. Python-try_finally使用
try: try_suite finally: do_finally
- 如果try語句沒有捕獲錯誤,程式碼執行do_finally語句
- 如果try語句捕獲錯誤,程式首先執行do_finally語句,然後將捕獲的錯誤交給python解釋器處理
- 5. Python -try-except-else-finally
try: try_suite except: do_except finally: do_finally
- 若try語句沒有捕獲異常,執行完try程式碼段後,執行finally
- 若try捕獲異常,先執行except處理錯誤,然後執行finally
- 6. Python-with_as語句
with context [as var]: with_suite
- with語句用來取代try_except_finall語句,使程式碼更簡潔
- context表達式回傳是一個物件
- var用來保存context回傳對象,單一傳回值或元祖
- with_suite使用var變數來對context回傳物件進行操作
- with語句實質是上下文管理:
- 上下文管理協定:包含方法
- __enter__()
和
__exit()__
,支援該協定的物件要實作這兩個方法 上下文管理器:定義執行with語句時要建立的執行階段上下文,負責執行with語句區塊上下文中的進入與退出操作 - 進入上下文管理員:調用管理器
- __enter__
方法,如果設定as var語句,var變數接受
__enter__()
方法傳回值 退出上下文管理器:調用管理器 - __exit__
方法
class Mycontex(object): def __init__(self, name): self.name = name def __enter__(self): print "__enter__" return self def do_self(self): print "do_self" def __exit__(self, exc_type, exc_val, exc_tb): print "__exit__" print "Error:", exc_type, " info:", exc_val if __name__ == "__main__": with Mycontex('test context') as f: print f.name f.do_self()
whith語句應用場景:
- 檔案操作
- #進程執行緒之間互斥對象,例如互斥鎖
- 支援上下文的其他物件
- 2. 標準異常和自動以異常
1. Python-assert和raise語句
- rais語句
- 語法格式:raise[exception[,args]]
- exception:異常類別
- #args:描述例外資訊的元組
- reise語句用於主動拋出異常
raise TypeError, 'Test Error'
raise IOError, 'File Not Exit'##assert語句
- 斷言語句:assert語句用來偵測表達式是否為真,如果為假,引發AssertionError錯誤
- 語法格式:assert expression[,args]
- experession:表達式
- args:判斷條件的描述訊息
-
assert 0, 'test assert'
assert 4==5, 'test assert'
2. Python-標準異常與自訂異常
- #python內建異常,程式執行前就已經存在
- python允許自訂例外,用來描述python中沒有涉及的異常情況
- 自訂異常必須繼承Exception類別
- 自訂異常只能主動觸發
-
class CustomError(Exception): def __init__(self, info): Exception.__init__(self) self.message = info print id(self) def __str__(self): return 'CustionError:%s' % self.message try: raise CustomError('test CustomError') except CustomError, e: print 'ErrorInfo:%d,%s' % (id(e), e)
更多Python錯誤與異常概念相關文章請關注PHP中文網!

Tomergelistsinpython,YouCanusethe操作員,estextMethod,ListComprehension,Oritertools

在Python3中,可以通過多種方法連接兩個列表:1)使用 運算符,適用於小列表,但對大列表效率低;2)使用extend方法,適用於大列表,內存效率高,但會修改原列表;3)使用*運算符,適用於合併多個列表,不修改原列表;4)使用itertools.chain,適用於大數據集,內存效率高。

使用join()方法是Python中從列表連接字符串最有效的方法。 1)使用join()方法高效且易讀。 2)循環使用 運算符對大列表效率低。 3)列表推導式與join()結合適用於需要轉換的場景。 4)reduce()方法適用於其他類型歸約,但對字符串連接效率低。完整句子結束。

pythonexecutionistheprocessoftransformingpypythoncodeintoExecutablestructions.1)InternterPreterReadSthecode,ConvertingTingitIntObyTecode,whepythonvirtualmachine(pvm)theglobalinterpreterpreterpreterpreterlock(gil)the thepythonvirtualmachine(pvm)

Python的關鍵特性包括:1.語法簡潔易懂,適合初學者;2.動態類型系統,提高開發速度;3.豐富的標準庫,支持多種任務;4.強大的社區和生態系統,提供廣泛支持;5.解釋性,適合腳本和快速原型開發;6.多範式支持,適用於各種編程風格。

Python是解釋型語言,但也包含編譯過程。 1)Python代碼先編譯成字節碼。 2)字節碼由Python虛擬機解釋執行。 3)這種混合機制使Python既靈活又高效,但執行速度不如完全編譯型語言。

UseeAforloopWheniteratingOveraseQuenceOrforAspecificnumberoftimes; useAwhiLeLoopWhenconTinuingUntilAcIntiment.forloopsareIdealForkNownsences,而WhileLeleLeleLeleLeleLoopSituationSituationsItuationsItuationSuationSituationswithUndEtermentersitations。

pythonloopscanleadtoerrorslikeinfiniteloops,modifyingListsDuringteritation,逐個偏置,零indexingissues,andnestedloopineflinefficiencies


熱AI工具

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

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

Undress AI Tool
免費脫衣圖片

Clothoff.io
AI脫衣器

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

熱門文章

熱工具

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

VSCode Windows 64位元 下載
微軟推出的免費、功能強大的一款IDE編輯器

PhpStorm Mac 版本
最新(2018.2.1 )專業的PHP整合開發工具

SAP NetWeaver Server Adapter for Eclipse
將Eclipse與SAP NetWeaver應用伺服器整合。

Safe Exam Browser
Safe Exam Browser是一個安全的瀏覽器環境,安全地進行線上考試。該軟體將任何電腦變成一個安全的工作站。它控制對任何實用工具的訪問,並防止學生使用未經授權的資源。