Catching previously caught exception type KeyboardInterrupt
9 except (KeyboardInterrupt, EOFError):
10 print()
11 exit()
12 except (BaseException, KeyboardInterrupt) as e:13 print(e)
14
15
Description
An exception should be caught only once in a try
-except
block.
It is useless to catch the previously caught exception later in other else blocks as the previous exception block handling the exception would be executed every time.
Not preferred
try:
1 / 0
except ZeroDivisionError:
print("Divided by zero")
except (OSError, ZeroDivisionError):
print("Handles an exception which was caught before.")
Preferred
try:
1 / 0
except ZeroDivisionError:
print("Divided by zero")
except OSError:
print("Handles a unique exception")