如何捕捉Python中的縮排錯誤異常?


當解析器發現不符合縮排規則的原始碼時,就會發生縮排錯誤。在匯入模組時可以捕捉到此錯誤,因為該模組將首次匯入時進行編譯。你無法在包含 try/except 塊的同個模組中捕獲此錯誤,因為有了此異常,Python將無法完成編譯模組,而且不會執行模組中的任何程式碼。

我們按如下方式重寫給定的程式碼,以處理此異常

示例

try:
def f():
z=['foo','bar']
for i in z:
if i == 'foo':
except IndentationError as e:
print e

輸出

"C:/Users/TutorialsPoint1/~.py", line 5
if i == 'foo':
^
IndentationError: expected an indented block


更新時間:2020 年 2 月 12 日

1k+ 次瀏覽

啟動您的 職業生涯

透過完成課程獲得認證

立即開始
廣告
© . All rights reserved.