Source

Adapted from my own handwritten and hand-typed notes from Year 1 to Year 3 of my EEE degree

Two Kinds of Error

Syntax errorException error
Whatgrammatical error in the coderun-time error
Examplemissing : at the end of a for line'5' + 4 gives a TypeError
Handlingcannot be handled, must fix the codecan be handled while running

try and except

The try block runs first. If any exception happens inside it, Python leaves the block and runs the except block.

a, b = '5', 4
try:
    print(a + b)
except:
    print('An error has occurred.')

To handle only one kind of error, name it. Several except blocks can treat different errors differently:

try:
    print(a + b)
except TypeError:
    print(int(a) + int(b))     # 9
except ZeroDivisionError:
    print('Cannot divide by zero')

Common Exception Names

ExceptionCause
KeyErrorkey not found in a dictionary
IndexErrorindex not found in the sequence
IOErrorI/O operation failed, e.g. a missing file in File Input and Output in Python
NameErroridentifier not found in the namespace
TypeErroroperation invalid for the data type
ValueErrorinvalid value for the operation
ZeroDivisionErrordivision by zero

else and finally

Optional extra blocks:

  • else runs only if no exception happened in try
  • finally runs always, whether or not an exception happened
try:
    number = int('3.0')
except:
    print('An error occurred.')    # this runs, int('3.0') is a ValueError
else:
    print('It was a success!')
finally:
    print('I hope you have enjoyed my code.')

Raising an Exception

raise triggers an exception manually, with a custom message:

x = -1
if x < 0:
    raise ValueError('x must be positive.')

Putting It Together

numberstr = input('Enter a number from 0 to 10: ')
try:
    number = float(numberstr)              # ValueError if non-numeric
    if not 0 <= number <= 10:
        raise RuntimeError('Out of range')
except ValueError:
    print('Not a number.')
except RuntimeError as e:
    print(e)
else:
    print('Registered', number, 'as float')