Python try catch exception statement is used to handle exceptions in python code, but there are some little differences of python exception handling between python 3 and python 2. Below example will show you the differences, let’s look at it.
Handle Exception In Python 2
try: raise except Exception, e: print (e) return false
Handle Exception In Python 3
try: raise except Exception as e: print (e) return false
The key difference is: Python 3 has an
as keyword when catch exception, please pay attention to it.
Common Exception List
- Exception : The base class for all exceptions.
- AttributeError : Raised when attribute assignment fails.
- IOError : Raised when attempting to open a file that does not exist.
- IndexError : Raised when using an index that does not exist in the sequence.
- KeyError : Thrown when using a key that the map does not contain.
- NameError : Raised when the name (variable) cannot be found.
- SyntaxError : Raised when the code uses wrong syntax.
- TypeError : Thrown when use wrong python type objct.
- ValueError : Thrown when python object has an inappropriate value.
- ZeroDivisionError : Raised when the second parameter of a division operation is 0.