Exceptions

An exception is what python uses to flag a exceptional behavior in a program. These are objects that if not dealt with by the program will terminate the program with an error or traceback.

>>> 1/0
Traceback (most recent call last):
File "", line 1, in
1/0
ZeroDivisionError: integer division or modulo by zero
>>>

As you can see a ZeroDivisionError has been raised. To see a list of all the exception available to you use:

>>> import exceptions
>>> dir(exceptions)
['ArithmeticError', 'AssertionError', 'AttributeError', 'BaseException', 'BufferError', 'BytesWarning', 'DeprecationWarning', 'EOFError', 'EnvironmentError', 'Exception', 'FloatingPointError', 'FutureWarning', 'GeneratorExit', 'IOError', 'ImportError', 'ImportWarning', 'IndentationError', 'IndexError', 'KeyError', 'KeyboardInterrupt', 'LookupError', 'MemoryError', 'NameError', 'NotImplementedError', 'OSError', 'OverflowError', 'PendingDeprecationWarning', 'ReferenceError', 'RuntimeError', 'RuntimeWarning', 'StandardError', 'StopIteration', 'SyntaxError', 'SyntaxWarning', 'SystemError', 'SystemExit', 'TabError', 'TypeError', 'UnboundLocalError', 'UnicodeDecodeError', 'UnicodeEncodeError', 'UnicodeError', 'UnicodeTranslateError', 'UnicodeWarning', 'UserWarning', 'ValueError', 'Warning', 'WindowsError', 'ZeroDivisionError', '__doc__', '__name__', '__package__']
>>>

Exception handling allows the programmer to catch the error and do something about it, rather than letting the program fail. We will use the divide by 0 error above to show you how to catch an exception.

# catch_exception.py
num1 = input('Enter first number: ')
num2 = input('Enter second number: ')
try:
result = num1/num2
print result
except ZeroDivisionError:
print "You can't divide by zero"

Tags: