Python エラーと例外 ErrorとException
Publish date: 2021-03-09
Last updated: 2021-03-09
Last updated: 2021-03-09
Pythonのエラーと例外について解説します。
構文のエラー
Pythonの構文解析中にエラーが発生するとSyntaxErrorが送出される。
a = 123"
# => SyntaxError: EOL while scanning string literalインデントが正しくない場合はSyntaxErrorのサブクラスIndentationErrorのエラーが送出する。
if 1 == 1:
print(1)
print(2)
# => IndentationError: unindent does not match any outer indentation level例外
Python実行時のエラーは、例外(exception)と呼ばれます。
try-finally, try-except-else-finally文 で例外が発生した場合の処理を管理できる。
try:
number = 10 / 0
#""/ 2
except ZeroDivisionError as e:
print(e)
except TypeError as e :
print(e)
except Exception as e:
print(e)
else:
print("else")
finally:
print("finally") raise
raiseで例外を発生させることができる。
try:
raise Exception('SomeException','SomeArgs')
except Exception as ex:
print(type(ex)) # => <class 'Exception'>
print(ex.args) # => ('SomeException', 'SomeArgs')
print(ex) # => ('SomeException', 'SomeArgs')raiseの後に型名を指定しても例外を送出できる。
try:
raise ValueError
except Exception as ex:
print(type(ex)) # => <class 'ValueError'>
print(ex.args) # => ()