Learn › Class 12 › Computer Science / Informatics Practices › Python revision, functions, exceptions
Exception handling
Example 1: Safe division of user input
Open one step at a time. Try the next step yourself first.
- Step 1. try: n = int(input('Number: ')); print(100 / n)
Show step 2
except ValueError: print('Please type a whole number')
Show step 3
except ZeroDivisionError: print('Cannot divide by zero')
Show step 4
finally: print('Done')
Show step 5
Typing 0 prints 'Cannot divide by zero' and then 'Done'.
Example 2: Following the flow
Open one step at a time. Try the next step yourself first.
- Step 1. try: print('A'); x = 1 / 0; print('B')
Show step 2
except ZeroDivisionError: print('C')
Show step 3
finally: print('D')
Show step 4
Output: A, C, D. 'B' is skipped because the exception happens first.