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 error | Exception error | |
|---|---|---|
| What | grammatical error in the code | run-time error |
| Example | missing : at the end of a for line | '5' + 4 gives a TypeError |
| Handling | cannot be handled, must fix the code | can 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
| Exception | Cause |
|---|---|
KeyError | key not found in a dictionary |
IndexError | index not found in the sequence |
IOError | I/O operation failed, e.g. a missing file in File Input and Output in Python |
NameError | identifier not found in the namespace |
TypeError | operation invalid for the data type |
ValueError | invalid value for the operation |
ZeroDivisionError | division by zero |
else and finally
Optional extra blocks:
elseruns only if no exception happened intryfinallyruns 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')