DevelopmentLanguage:Python:Basics08
8.基本編-例外処理(Python)
例外処理(try)
コード構造
[処理1]でエラーが発生しても、「処理2」を実行する。
try:
処理1
except:
処理2
except:
例外結果を取得したい場合
[処理]で発生した例外結果を[ex]に格納し、print(ex)で出力する。
try:
処理
except Exception as ex:
print(ex)
#name '処理' is not defined
特定の例外結果を取得したい場合
下記から該当するexception名を記載して取得する。
https://docs.python.org/ja/3/library/exceptions.html#BaseException
finally:
「try文」で何が起きても、「finally文」を実行する。
try:
処理
except NameError as ex:
print(ex)
finally:
print('end')
# name '処理' is not defined
# end
try:
処理
except SyntaxError as ex:
print(ex)
finally:
print('end')
# end
# Traceback (most recent call last):
# File "c:\Users\admin\Desktop\tempCodeRunnerFile.py", line 2, in <module>
# 処理
# NameError: name '処理' is not defined
else:
「try文」が成功した場合に「else文」を実行する。
try:
print('start')
except SyntaxError as ex:
print(ex)
else:
print('done')
finally:
print('end')
# start
# done
# end
DevelopmentLanguage/Python/Basics08.txt · 最終更新: by admin