創新互聯www.cdcxhl.cn八線動態BGP香港云服務器提供商,新人活動買多久送多久,劃算不套路!

今天就跟大家聊聊有關怎么處理python中的異常,可能很多人都不太了解,為了讓大家更加了解,小編給大家總結了以下內容,希望大家根據這篇文章可以有所收獲。
異常是什么
異常是可以修改程序控制流程的事件。
在 Python 中,異??梢员诲e誤自動觸發,也可以由你的代碼手動觸發。
我們將學習4種處理異常的語句,第一種有兩種形式,最后一種是 Python 2.6 和 Python 3.0 中的可選擴展。
try/except:捕捉并恢復 Python 自動觸發的或自己代碼中的異常。
try/finally:無論異常是否發生,執行清理操作。
raise:手動觸發一個異常。
with/as:在 Python 2.6 ,3.0 或更新的版本中實現上下文管理器。
try/except 語句
try: statements # Run this main action first except name1: # Run if name1 is raised during try block statements except (name2, name3): # Run if any of these exceptions occur statements except name4 as var: # Run if name4 is raised, assign instance raised to var statements except: # Run for all other exceptions raised statements else: statements # Run if no exception was raised during try block
list_of_numbers = [number for number in range(1, 100)] print(list_of_numbers)
dictionary_of_numbers = {}
for number in list_of_numbers:
dictionary_of_numbers[number**2] = number
try:
index = list_of_numbers.index(2)
value = dictionary_of_numbers[index]
except (ValueError, KeyError):
print('Error Raised, but Controlled! ')
else:
# This executes ONLY if no exception is raised
print('Getting number at position %d : %d' % (index, value))
finally:
# Do cleanup operations
print('Cleaning UP')try/finally 語句
try/finally 是 try 語句的一種形式,finally 語句是 try 之后無論是否出現異常都要執行的語句。
try: statements # Run this action first finally: statements # Always run this code on the way out
with/as 上下文管理器
Python 2.6 和 3.0 引入了一個新的異常相關的語句-with 和可選的 as 子句。with語句允許開發者創建上下文管理器,上下文管理器就是允許你可以自動地開始和結束一些事情。例如,你可能想要打開一個文件,然后寫入一些內容,最后再關閉文件。這就是上下文管理器中一個最經典的示例。事實上,當你利用with語句打開一個文件時,Python替你自動創建了一個上下文管理器。
上下文管理器簡介
基本用法
with expression [as variable]: with-block
經典用法
with open(r'C:\misc\data') as myfile: for line in myfile: print(line) # ...more code here...
使用多個上下文管理器
with open('script1.py') as f1, open('script2.py') as f2:
for (linenum, (line1, line2)) in enumerate(zip(f1, f2)):
if line1 != line2:
print('%s\n%r\n%r' % (linenum, line1, line2))工作原理
上下文管理器必須包含 __enter__ 和 __exit__ 方法。
__enter__ 方法被自動調用,如果存在 as 子句,返回值就被賦值給 as 后的變量,沒有就直接丟棄。
嵌套在 with 語句下的代碼被執行。
如果 with 語句中的代碼拋出異常, __exit__(type, value, traceback) 方法就會被調用。參數值是和 sys.exc_info() (Python 內置函數)函數返回值相同的值。如果這個方法返回了一個 false 值,異常就會被重新拋出,否則異常終止。異常重新拋出是以常規方式拋出的,因此在 with 語句外捕獲。
如果 with 語句里的代碼塊沒有拋出異常,__exit__ 方法仍舊會被調用,但是參數會被置為 None。
異常用法
class TraceBlock:
def message(self, arg):
print('running ' + arg)
def __enter__(self):
print('starting with block')
return self
def __exit__(self, exc_type, exc_value, exc_tb):
if exc_type is None:
print('exited normally\n')
else:
print('raise an exception! ' + str(exc_type))
return False # Propagatewith TraceBlock() as action:
action.message('test 1')
print('reached')with TraceBlock() as action:
action.message('test 2')
raise TypeError()
print('not reached')用戶自定義異常
class AlreadyGotOne(Exception): pass def gail(): raise AlreadyGotOne()
try:
gail()
except AlreadyGotOne:
print('got exception')class Career(Exception):
def __init__(self, job, *args, **kwargs):
super(Career, self).__init__(*args, **kwargs)
self._job = job
def __str__(self):
return 'So I became a waiter of {}'.format(self._job)
raise Career('Engineer')看完上述內容,你們對怎么處理python中的異常有進一步的了解嗎?如果還想了解更多知識或者相關內容,請關注創新互聯-成都網站建設公司行業資訊頻道,感謝大家的支持。
分享文章:怎么處理python中的異常-創新互聯
當前鏈接:http://www.yijiale78.com/article42/phhhc.html
成都網站建設公司_創新互聯,為您提供域名注冊、靜態網站、手機網站建設、外貿網站建設、ChatGPT、用戶體驗
聲明:本網站發布的內容(圖片、視頻和文字)以用戶投稿、用戶轉載內容為主,如果涉及侵權請盡快告知,我們將會在第一時間刪除。文章觀點不代表本網站立場,如需處理請聯系客服。電話:028-86922220;郵箱:631063699@qq.com。內容未經允許不得轉載,或轉載時需注明來源: 創新互聯