LoginSignup
3
4

More than 1 year has passed since last update.

Pythonのループ+try/except/finally句+break/continueの挙動

Posted at

動きに確信が持てなかったので検証しました。

検証

コード1

while True:
    try:
        print('a')
        raise Exception()
    except Exception:
        print('b')
        break
    finally:
        print('c')

実行結果1

$ python3 loop.py
a
b
c

コード2

for i in range(0, 2):
    try:
        print('a')
        if i == 0:
            raise Exception()
    except Exception:
        print('b')
        continue
    finally:
        print('c')

実行結果2

$ python3 loop.py
a
b
c
a
c

結論

ループ中のexcept句でbreakcontinueが実行された場合も、breakcontinueによる処理の前にfinally句の処理が実行される。

3
4
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
3
4