Skip to content

Language

Sign in

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.

  1. Step 1. try: n = int(input('Number: ')); print(100 / n)
  2. Show step 2

    except ValueError: print('Please type a whole number')

  3. Show step 3

    except ZeroDivisionError: print('Cannot divide by zero')

  4. Show step 4

    finally: print('Done')

  5. 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.

  1. Step 1. try: print('A'); x = 1 / 0; print('B')
  2. Show step 2

    except ZeroDivisionError: print('C')

  3. Show step 3

    finally: print('D')

  4. Show step 4

    Output: A, C, D. 'B' is skipped because the exception happens first.

Reviewed by EduFlint team on 1 Dec 2026 · version 1

Written by us for this site. Independent; not affiliated with NCERT or CBSE.

Report a mistake

Looking for another topic?