LoginSignup
0
0

More than 3 years have passed since last update.

【Python】try文がcatchされず正常終了されたのかをtry-elseで判定する方法(備忘録)

Last updated at Posted at 2021-04-01

try文がcatchされたのか、catchされず(Exceptionが発生せず)正常終了されたのかを判定する方法。
他の言語のクセでbool型で判定しがちだったけどこれは便利。

try-else

hoge = 1

try:
    hoge = hoge / 10
except Exception as e:
    print('エラーだよ Exception:', e)
else:
    print('正常終了したよ')
finally:
    print('try文が終了したよ')
正常終了したよ
try文が終了したよ

ちなみにhoge = 'hoge'だと

エラーだよ Exception: unsupported operand type(s) for /: 'str' and 'int'
try文が終了したよ

bool型での判定

よく書きがちだった方法

isError = False
hoge = 1

try:
    hoge = hoge / 10
except Exception as e:
    isError = True
    print('エラーだよ Exception:', e)
finally:
    if not isError:
        print('正常終了したよ')
    print('try文が終了したよ')

以上

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0