如何在 python 中捕獲 IndentationError 異常?


每當編譯器發現原始碼不符合縮排規則時,就會發生縮排錯誤(IndentationError)。在匯入模組時,可以捕獲該異常,因為模組將在第一次匯入時進行編譯。無法在包含 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-02-12

1K+ 瀏覽

開啟 職業生涯

透過完成課程獲得認證

開始學習
廣告
© . All rights reserved.