Exception handling in Python
Exception happens when procedure execution hits an unexpected
condition. Bellows are some common samples:
- Visit the index beyond the len of list/tuple
- Referring an non-existing variable
- Convert an inappropriate type
- Mixing data types without appropriate coercion
Traditional ways we handle the exception:
- Keep silent, substitute a default value and continuous (not good. caller not aware)
- Return an ‘error’ value (not perfect. caller has to deal with the return code)
- Stop execution and siginal error condition (raise an exception)
common errors
Here are the common errors we will see in Python programing
- SyntaxError: Python can’t parse program
- NameError: local or global name not found
- AttributeError: attribute reference fails
- TypeError: operand doesn’t have correct type
- ValueError: operand type okay, but value is illegal
- IOError: IO system reports malfunction (e.g. file not found)
Python Exception handling block:
Try:# main program which may cause exception
except “exception type1”, “exception value 1”:
exception handle block 1
except “exception type2”, “exception value 2”:
exception handle block 2
… …
except “exception typen”, “exception value n”:
exception handle block n
else:
#program block if none of the exceptions are raised
finally:
#the block which will be executed no matter if there is any exception.
No comments:
Post a Comment