例外処理とは?
例外処理とは何なのか。簡単に言うと、コンピュータが命令を実行した際に、
例外が発生した場合の処理を決めることです。
try-exceptを使用することで例外処理を行うことができます。
例外処理の書き方
下のようなPythonのスクリプトがあります。
import os
list_file = os.listdir("/root/test")
print(list_file)
os.listdir はosモジュールの関数で、
指定したディレクトリパス配下にあるファイルやディレクトリをリストとして取得します。
上記のコードであれば、/root/testディレクトリ配下のファイルやディレクトリを取得しようとします。
しかし、/root/test 以下にファイルが何もない場合、以下のエラーが出てしまいます。
$ python test.py
Traceback (most recent call last):
File "test.py", line 4, in <module>
list_file = os.listdir("/root/test")
FileNotFoundError: [Errno 2] No such file or directory: '/root/test'
これが、コンピュータが命令を実行したときに発生した例外処理です。
では、try-exceptを使用して、例外発生時の処理を書いてみましょう。
書き方はこんな感じです。
try:
<例外が発生する可能性のある処理>
except <例外型>:
<例外型と同じ例外発生時の処理(今回であればFileNotFoundError)>
では、これにならってコードを書いてみましょう。
今回、FileNotFoundErrorの例外発生時には"Directory that you specified doesn't exist"と表示したいと思います。
以下のようにコードを修正し、実行してみます。
import os
try:
list_file = os.listdir("/root/test")
print(list_file)
except FileNotFoundError:
print("Directory that you specified doesn't exist")
実行すると、、、
$ python test.py
Directory that you specified doesn't exist
例外処理が行われました!
例外オブジェクト(例外型のクラスから作られたオブジェクト)を変数に格納し、
エラーの詳細情報を表示させることもできます。
以下のようにコードを修正します。
import os
try:
list_file = os.listdir("/root/test")
print(list_file)
except FileNotFoundError as e:
print("Directory that you specified doesn't exist")
print(e)
as e を加え、printで表示させるようにしました。実行すると、、
$ python test.py
Directory that you specified doesn't exist
[Errno 2] No such file or directory: '/root/test'
詳細なエラー内容が出ましたね。
except節は複数追加することも可能です。
Finallyの使い方
finally を使用すると、例外発生の有無に関わらず、最後に行う処理を決めることができます。
以下のコードを用意します。
import os
try:
list_file = os.listdir("/root/test")
print(list_file)
except FileNotFoundError as e:
print("Directory that you specified doesn't exist")
print(e)
finally:
print("END")
finally節を追加しました。実行すると、、、
$ python test.py
Directory that you specified doesn't exist
[Errno 2] No such file or directory: '/root/test'
END
最後にENDと表示されました!
Exception の使い方
Exception を使用すると、システム終了以外の全例外をキャッチすることができます。
以下のコードを用意します。
import os
try:
list_file = os.listdir("/root/test")
print(list_file)
except Exception as e:
print(e)
print("END")
実行すると、、、
[Errno 2] No such file or directory: '/root/test'
END
例外処理が行われましたね。
以上が例外処理の概要です!