本文實例講述了Python錯誤和異常及訪問錯誤消息。分享給大家供大家參考,具體如下:
錯誤和異常
- 當 Python 無法解析代碼時,就會發生語法錯誤,因為我們沒有遵守正確的 Python 語法。
- 當在程序執行期間出現意外情況時,就會發生異常,即使代碼在語法上正確無誤。Python 有不同類型的內置異常。
指定異常
可以指定要在
except
塊中處理哪個錯誤,如下所示:
try:
# some code
except ValueError:
# some code
現在它會捕獲
ValueError
異常,但是不會捕獲其他異常。如果我們希望該處理程序處理多種異常,我們可以在
except
后面添加異常元組。
try:
# some code
except (ValueError, KeyboardInterrupt):
# some code
或者,如果我們希望根據異常執行不同的代碼塊,可以添加多個
except
塊。
try:
# some code
except ValueError:
# some code
except KeyboardInterrupt:
# some code
處理除以零的案例:
def create_groups(items, num_groups):
try:
size = len(items) // num_groups
except ZeroDivisionError:
print("WARNING: Returning empty list. Please use a nonzero number.")
return []
else:
groups = []
for i in range(0, len(items), size):
groups.append(items[i:i + size])
return groups
finally:
print("{} groups returned.".format(num_groups))
print("Creating 6 groups...")
for group in create_groups(range(32), 6):
print(list(group))
print("\nCreating 0 groups...")
for group in create_groups(range(32), 0):
print(list(group))
正確的輸出應該是:
Creating 6 groups...
6 groups returned.
[0, 1, 2, 3, 4]
[5, 6, 7, 8, 9]
[10, 11, 12, 13, 14]
[15, 16, 17, 18, 19]
[20, 21, 22, 23, 24]
[25, 26, 27, 28, 29]
[30, 31]Creating 0 groups...
WARNING: Returning empty list. Please use a nonzero number.
0 groups returned.
訪問錯誤消息
在處理異常時,依然可以如下所示地訪問其錯誤消息:
try:
# some code
except ZeroDivisionError as e:
# some code
print("ZeroDivisionError occurred: {}".format(e))
應該會輸出如下所示的結果:
ZeroDivisionError occurred: division by zero
如果沒有要處理的具體錯誤,依然可以如下所示地訪問消息:
try:
# some code
except Exception as e:
# some code
print("Exception occurred: {}".format(e))
此處:
Exception
是所有內置異常的基礎類。
更多Python相關內容感興趣的讀者可查看本站專題:《Python入門與進階經典教程》、《Python字符串操作技巧匯總》、《Python列表(list)操作技巧總結》、《Python編碼操作技巧總結》、《Python數據結構與算法教程》、《Python函數使用技巧總結》及《Python文件與目錄操作技巧匯總》
希望本文所述對大家Python程序設計有所幫助。
更多文章、技術交流、商務合作、聯系博主
微信掃碼或搜索:z360901061
微信掃一掃加我為好友
QQ號聯系: 360901061
您的支持是博主寫作最大的動力,如果您喜歡我的文章,感覺我的文章對您有幫助,請用微信掃描下面二維碼支持博主2元、5元、10元、20元等您想捐的金額吧,狠狠點擊下面給點支持吧,站長非常感激您!手機微信長按不能支付解決辦法:請將微信支付二維碼保存到相冊,切換到微信,然后點擊微信右上角掃一掃功能,選擇支付二維碼完成支付。
【本文對您有幫助就好】元

