You might experience the traceback error message whenever something goes wrong with your code. If you are not, try with the following example which we divide a value with zero.
>>> def test():
1/0
>>> test()
Traceback (most recent call last):
File "<pyshell#24>", line 1, in <module>
test()
File "<pyshell#23>", line 2, in test
1/0
ZeroDivisionError: integer division or modulo by zero
1/0
>>> test()
Traceback (most recent call last):
File "<pyshell#24>", line 1, in <module>
test()
File "<pyshell#23>", line 2, in test
1/0
ZeroDivisionError: integer division or modulo by zero
try:
#your code (which might cause a runtime error)
except:
#your error-recovery code
finally:
#your housekeeping code
#your code (which might cause a runtime error)
except:
#your error-recovery code
finally:
#your housekeeping code
Let’s try to divide a value with zero in try/except statement.
>>> def test():
try:
1/0
except:
print 'error!'
>>> test()
error!
try:
1/0
except:
print 'error!'
>>> test()
error!
Be specific with your exceptions:
Except is great in catching of all the errors. Sometimes, you may want to catch the actual error so that you know how and what to recover when it happen. Take a look if the following example.>>> def test():
try:
1/0
except ZeroDivisionError:
print 'Can\'t divide by zero!'
>>> test()
error!
try:
1/0
except ZeroDivisionError:
print 'Can\'t divide by zero!'
>>> test()
error!
Class Name | Description |
---|---|
Exception | The base class for all exceptions |
AttributeError | Raised when attribute reference or assignment fails |
Exception | The base class for all exceptions |
IOError | Raised when trying to open a nonexistent file (among other things) |
IndexError | Raised when using a nonexistent index on a sequence |
KeyError | Raised when using a nonexistent key on a mapping |
NameError | Raised when a name (variable) is not found |
SyntaxError | Raised when the code is ill-formed |
TypeError | Raised when a built-in operation or function is applied to an object of the wrong type |
ValueError | Raised when a built-in operation or function is applied to an object with the correct type, but with an inappropriate value |
ZeroDivisionError | Raised when the second argument of a division or modulo operation is zero |
More Than One except Clause:
The try/except statement allow you to catch more than one exception. The following example show you how you can do that in Python. Let’s modify the previous example so that test() function will take two arguments.>>> def test(val1, val2):
try:
val1/val2
except ZeroDivisionError:
print 'Can\'t divide by zero!'
except TypeError:
print 'Incorrect type of argument!'
except:
print 'Other error!'
try:
val1/val2
except ZeroDivisionError:
print 'Can\'t divide by zero!'
except TypeError:
print 'Incorrect type of argument!'
except:
print 'Other error!'
>>> test(1,0)
Can't divide by zero!
Can't divide by zero!
>>> test('abc', 8)
Incorrect type of argument!
Incorrect type of argument!
Catching two or more Exceptions with One Block:
Python allow you to catch more than 1 exception in the same block. Let’s modify the test() function again so that it group both ZeroDivisionError and TypeError in the same block.>>> def test(val1, val2):
try:
val1/val2
except (ZeroDivisionError, TypeError):
print 'Invalid type or can\'t divide by zero!'
except:
print 'Other error!'
try:
val1/val2
except (ZeroDivisionError, TypeError):
print 'Invalid type or can\'t divide by zero!'
except:
print 'Other error!'
>>> test(1,0)
Invalid type or can't divide by zero!
Invalid type or can't divide by zero!
>>> test('abc', 8)
Invalid type or can't divide by zero!
Invalid type or can't divide by zero!
Error log:
Often, you may create a program with logging enable so that it write the log to a file when there is an error in the program. The following is a sample program that prints out the exception.>>> def test():
try:
1/0
except Exception, e:
print 'Error: ' + str(e)
try:
1/0
except Exception, e:
print 'Error: ' + str(e)
>>> test()
Error: integer division or modulo by zero
Error: integer division or modulo by zero
Finally:
The finally clause is used to do housekeeping after a possible exception. The finally clause will be executed, no matter what exceptions occur in the try clause.>>> def test():
try:
1/0
except Exception, e:
print 'Error: ' + str(e)
finally:
print 'Remember: Do not divide value by zero!'
try:
1/0
except Exception, e:
print 'Error: ' + str(e)
finally:
print 'Remember: Do not divide value by zero!'
>>> test()
Error: integer division or modulo by zero
Remember: Do not divide value by zero!
Error: integer division or modulo by zero
Remember: Do not divide value by zero!
Python Tutorial: Exceptions