Python exception handling

  • use keywords try and except to handle an exception
  • example:
    a = input('type an number:')
    b = input('type another:')
    a = int(a)
    b = int(b)
    
    # what if user enters b = 0?
    # this is not allowed and will throw an exception
    
    try:
      print(a / b)
    except ZeroDivisionError:
      print('b cannot be zero.')

Copyright © 2022