エラー辞典

KeyboardInterrupt

実行中のプログラムに対して、ユーザーがCtrl+Cを押して中断したときに発生する例外です。

原因

ターミナルで実行中のプログラムに対して、キーボードから中断操作が行われたことが原因です。エラーというより「ユーザーの意図した操作」です。

エラーになるコード例

import time
print('処理中... Ctrl+Cで中断できます')
while True:
    time.sleep(1)
KeyboardInterrupt

修正版

import time
try:
    while True:
        time.sleep(1)
except KeyboardInterrupt:
    print('処理を中断しました')

よくある間違い

  • 無限ループのプログラムでKeyboardInterruptを想定しておらず、中断時に後片付け処理が行われない
  • except Exceptionで捕まると思い込んでしまう(KeyboardInterruptもSystemExitと同様、Exceptionの外側にある特別な例外です)

← エラー辞典に戻る