Pythonの例外処理-try,except,finally,elseの使い方-

2021/01/14PythonPythonの基本

記事内に広告が含まれています。

Pythonでは文や式が構文的に正しくても、実行しようとしたときにエラーが発生し検出されたエラーは 例外 (exception) と呼ばれ、そのエラーを取得して対応することができます。

通常はエラーが発生しうる箇所を「try,except,finally,else」で囲ってプログラムが中断しないようにコードを記述します。

スポンサーリンク

Pythonの例外処理

Pythonの例外処理は通常は「try … except」で囲まれたブロックで処理を行います。

try :
    print( 1 / 0 )
    i = 1 + 1
except ZeroDivisionError as e:
    print("catch ZeroDivisionError:", e)

上記のコードを実行すると

catch ZeroDivisionError: division by zero

となり0で割り算を実行した場合に発生する例外「ZeroDivisionError」をcatchして「i = 1 + 1」を実行することなく処理を終了していることがわかります。

複数の例外を切り分けてcatchする

Pythonの例外処理は複数の例外エラーを認識し処理を分けることができます。

複数の例外は「except」を並べて記述します。

try :
    i = int( "z" )
except ZeroDivisionError as e:
    print("catch ZeroDivisionError:", e)
except ValueError as e:
    print("catch ValueError:", e)
except Exception as e:
    print("catch other error:", e)

上記のコードを実行すると

catch ValueError: invalid literal for int() with base 10: 'z'

と例外エラー「ValueError」をcatchしたことがわかります。

例外が発生してもしなくても必ず行う処理を記述する「finally」

finallyにはtry内で例外エラーが発生しても、しなくても必ず実行される処理ブロックを記述します。

先ずは例外エラーが発生する場合。

try :
    i = int( "z" )
except ZeroDivisionError as e:
    print("catch ZeroDivisionError:", e)
except ValueError as e:
    print("catch ValueError:", e)
except Exception as e:
    print("catch other error:", e)
finally:
    print("finally block")

上記のコードを実行すると

catch ValueError: invalid literal for int() with base 10: 'z'
finally block

次に例外エラーが発生しない場合。

try :
    i = int( "10" )
except ZeroDivisionError as e:
    print("catch ZeroDivisionError:", e)
except ValueError as e:
    print("catch ValueError:", e)
except Exception as e:
    print("catch other error:", e)
finally:
    print("finally block")

上記のコードを実行すると

finally block

と例外エラーが発生しても、しなくても「finally」ブロックは実行されているのがわかります。

例外エラーが発生しなかった時のみ実行される「else」

elseはtry内で例外エラーが発生しなかった時のみに実行されるブロックです。

先ずは例外エラーが発生しなかった場合。

try :
    i = int( "10" )
except ZeroDivisionError as e:
    print("catch ZeroDivisionError:", e)
except ValueError as e:
    print("catch ValueError:", e)
except Exception as e:
    print("catch other error:", e)
else:
    print("else block")

上記のコードを実行すると

else block

次に例外エラーが発生した場合のelseブロック。

try :
    i = int( "z" )
except ZeroDivisionError as e:
    print("catch ZeroDivisionError:", e)
except ValueError as e:
    print("catch ValueError:", e)
except Exception as e:
    print("catch other error:", e)
else:
    print("else block")

上記のコードを実行すると

catch ValueError: invalid literal for int() with base 10: 'z'

とelseブロックが実行されませんでした。

新たな例外エラーを発生させるraise

Pythonでは新たに例外を発生させる「raise」文が用意されています。

以下の例では内側のtryで発生した例外エラー「ValueError」をcatchし、新たに例外エラー「ZeroDivisionError」を発生させています。

try :
    try :
        i = int( "z" )
    except ValueError as e:
        print("catch ValueError:", e)
        raise ZeroDivisionError( "実験でエラーを変える" )
    except Exception as e:
        print("catch other error:", e)
except ZeroDivisionError as e:
    print("outside catch ZeroDivisionError:", e)
except Exception as e:
    print("outside catch other error:", e)

上記のコードを実行すると

catch ValueError: invalid literal for int() with base 10: 'z'
outside catch ZeroDivisionError: 実験でエラーを変える

と例外エラー「ValueError」が例外エラー「ZeroDivisionError」に変わって通知されていることがわかります。

まとめ

Pythonでは「try,except,finally,else」を使って様々な例外エラー処理を記述することができます。

システムトラストでは一緒に働いていただける仲間を募集中です。
記事内に広告が含まれています。
株式会社システムトラスト

システムトラストでは、システムエンジニア、プログラマーなどを随時募集中です。気軽にご相談ください。

お問合せ