try節とexcept節編集

try と except のある構文を用いて、例外が発生した時の処理を記述できる。

try:
    例外の発生する可能性のある処理
except:
    例外発生時に行う処理

例外の起きそうな処理を、tryブロックに書く。tryブロック内で数値を0で割るなどの処理が発生すると、エラーとして認識され、exceptブロックの処理にうつり、exceptブロック内の処理が行われる。

try:
    print("3を入力した整数aで割るプログラム。")
    x = int(input())
    a = 3 / x
    print(a)
except:
    print("エラーが発生しました。")

上記のプログラムでは、もし0で割るなどの例外が発生すると、exceptブロックにある処理が実行されるので、「エラーが発生しました。」が表示される。また、print(a)が実行されるよりも先にエラーが発生するため、先にexceptブロックに処理が移るので、計算結果の3 / xは表示されない。

なお、もし正常に数値を入力するなどして、例外が発生しなければ、けっして「エラーが発生しました。」は表示されずに、3 / xの計算結果が表示される。

たとえば、入力の数値として、数「2」を入力すると、3 / 2の計算結果である「1.5」が表示され、そのままプログラムが終わる。


なお、tryブロックの外で例外が発生しても、exceptには処理は移動せずに、プログラムのエラーにより終了する。

print("3を入力した整数aで割るプログラム。")
x = int(input())
a = 3 / x

try:
    print(a)
except:
    print("エラーが発生しました。")

たとえば、上記のプログラムで、「0」を入力すると、「エラーが発生しました。」は表示されない。0を入力してエンターキーを押した直後に、インタープリターによりエラーメッセージ「ZeroDivisionError: division by zero」などのメッセージが表示され、そしてプログラムは終了する。

else節編集

elseブロックの処理は、例外が発生しなかった場合に、最後に行われる処理である。

finally節編集

finallyブロックの処理は、例外が発生しても発生しなくても、どちらの場合にも、最後に行われる処理である。

try:
    print("3を入力した整数aで割るプログラム。")
    x = int(input())
    a = 3 / x
    print(a)
except:
    print("エラーが発生しました。")
finally:
    print("計算を終了します。")

return と finally編集

return と finally
def div(n, d) :
    try :
        return n / d
    except Exception as e:
        print(e)
    finally :
        print("div(%s, %s) -- finally" % (n, d))

print("div(1, 2) = %s" % div(1, 2))
print("div(1, 0) = %s" % div(1, 0))
print("div(0, 0) = %s" % div(0, 0))
実行結果
div(1, 2) -- finally
div(1, 2) = 0.5
division by zero
div(1, 0) -- finally
div(1, 0) = None
division by zero
div(0, 0) -- finally
div(0, 0) = None
try文にfinally節を持つ言語では「tryブロックで例外を出さずのreturn文に達したとき、finally節を実行するか?」が問題になります。
Puthonでは、return文に達してもfinally節が実行されます。

例外の場合わけ編集

pythonの例外処理では、生じた例外クラスに応じての場合わけもできます。

try:
    例外の発生する可能性のある処理
except 例外クラスA:
    例外発生時に行う処理
except 例外クラスB:
    例外発生時に行う処理

のように、生じた例外クラスにおうじて、exceptのあとに例外クラスを指定します。


「ゼロで割り算できない」という例外の場合は組込み例外 ZeroDivisionError を、exceptの直後に記述することにより、例外クラスを指定します。

よって、この部分のコード記述は、

except ZeroDivisionError :

のようになります。

ほかにも例外クラスはあります。例外クラスが、型(かた)についてのエラーの場合には組込み例外 ValueErorrを、exceptの直後に記述することにより、例外クラスを指定します。なお、「型」とは、「整数型」とか「文字列型」とかのことです。

つまり、この場合の、この部分のコード記述は、

except ValueError :

のようになります。

まとめると、

try:
    例外の発生する可能性のある処理
except ZeroDivisionError :
    ゼロで割り算したことによる例外発生の時に行う処理
except ValueError :
    型のミスによる例外発生の時に行う処理
else :
    例外が上がらなかったときの処理
finally :
    例外の有無に関わらす実行する処理

のようになります。

なお、エラーを種類を指定するキーワードは、上記のZeroDivisionError や ValueError の他にも、たくさん、あります。

コード例
def divide_with_exception(n, d):
    try:
        return n / d
    except ZeroDivisionError as e:
        print('catch ZeroDivisionError:', e)
    except TypeError as e:
        print('catch TypeError:', e)
    finally:
        print('finally')
    print("out of try block")

x = divide_with_exception(1, 2)
print("1 / 2 => ", x)
x = divide_with_exception(1, 0)
print("1 / 0 => ", x)
x = divide_with_exception("ABC", 0)
print('"ABC" / 0 => ', x)
実行結果
finally
1 / 2 =>  0.5
catch ZeroDivisionError: division by zero
finally
out of try block
1 / 0 =>  None
catch TypeError: unsupported operand type(s) for /: 'str' and 'int'
finally
out of try block
"ABC" / 0 =>  None
例外が発生しなかったときも、'finally'は表示されますが、'out of try block'は例外が発生したときだけ表示されます。
これは、例外が上がらなければそのまま return が実行され関数を終えているからです。
例外が上がったときの戻り値は None になっていることにも注意してください。

組込み例外一覧編集

__builtins__ の要素のうち BaseExceptionのサブクラスを例外とし、例外と例外の __doc__ を表にしました。

組込み例外一覧
#print(issubclass(ValueError, Exception))
ex = []
for k in vars(__builtins__):
    try:
        if eval(f"issubclass({k}, BaseException)"):
            ex.append(k)
    except TypeError:
        pass

print(f"""\
{{| class=wikitable
|+ 組込み例外
!例外!!__doc__\
""")

for k in sorted(ex):
    print(f"""\
|-
! {k}
| {eval(f"{k}.__doc__")}\
""")

print("|}")
組込み例外
例外 __doc__
ArithmeticError Base class for arithmetic errors.
AssertionError Assertion failed.
AttributeError Attribute not found.
BaseException Common base class for all exceptions
BlockingIOError I/O operation would block.
BrokenPipeError Broken pipe.
BufferError Buffer error.
BytesWarning Base class for warnings about bytes and buffer related problems, mostly

related to conversion from str or comparing to str.

ChildProcessError Child process error.
ConnectionAbortedError Connection aborted.
ConnectionError Connection error.
ConnectionRefusedError Connection refused.
ConnectionResetError Connection reset.
DeprecationWarning Base class for warnings about deprecated features.
EOFError Read beyond end of file.
EnvironmentError Base class for I/O related errors.
Exception Common base class for all non-exit exceptions.
FileExistsError File already exists.
FileNotFoundError File not found.
FloatingPointError Floating point operation failed.
FutureWarning Base class for warnings about constructs that will change semantically

in the future.

GeneratorExit Request that a generator exit.
IOError Base class for I/O related errors.
ImportError Import can't find module, or can't find name in module.
ImportWarning Base class for warnings about probable mistakes in module imports
IndentationError Improper indentation.
IndexError Sequence index out of range.
InterruptedError Interrupted by signal.
IsADirectoryError Operation doesn't work on directories.
KeyError Mapping key not found.
KeyboardInterrupt Program interrupted by user.
LookupError Base class for lookup errors.
MemoryError Out of memory.
ModuleNotFoundError Module not found.
NameError Name not found globally.
NotADirectoryError Operation only works on directories.
NotImplementedError Method or function hasn't been implemented yet.
OSError Base class for I/O related errors.
OverflowError Result too large to be represented.
PendingDeprecationWarning Base class for warnings about features which will be deprecated

in the future.

PermissionError Not enough permissions.
ProcessLookupError Process not found.
RecursionError Recursion limit exceeded.
ReferenceError Weak ref proxy used after referent went away.
ResourceWarning Base class for warnings about resource usage.
RuntimeError Unspecified run-time error.
RuntimeWarning Base class for warnings about dubious runtime behavior.
StopAsyncIteration Signal the end from iterator.__anext__().
StopIteration Signal the end from iterator.__next__().
SyntaxError Invalid syntax.
SyntaxWarning Base class for warnings about dubious syntax.
SystemError Internal error in the Python interpreter.

Please report this to the Python maintainer, along with the traceback, the Python version, and the hardware/OS platform and version.

SystemExit Request to exit from the interpreter.
TabError Improper mixture of spaces and tabs.
TimeoutError Timeout expired.
TypeError Inappropriate argument type.
UnboundLocalError Local name referenced but not bound to a value.
UnicodeDecodeError Unicode decoding error.
UnicodeEncodeError Unicode encoding error.
UnicodeError Unicode related error.
UnicodeTranslateError Unicode translation error.
UnicodeWarning Base class for warnings about Unicode related problems, mostly

related to conversion problems.

UserWarning Base class for warnings generated by user code.
ValueError Inappropriate argument value (of correct type).
Warning Base class for warning categories.
ZeroDivisionError Second argument to a division or modulo operation was zero.