Introduction to Programming Exceptions

During your programming journey from absolute beginner to professional programmer you’ll encounter on number of exceptions. Exceptions will occur when something is wrong in your code, due to incorrect code of input. When exception occurs, the program immediately stops. The following code produce the ZeroDivisionError exception by trying to divide 7 by 0.

>>> a = 7
>>> b = 0
>>> print(a/b)
Traceback (most recent call last):
  File "", line 1, in 
ZeroDivisionError: integer division or modulo by zero
As you can see in previous example we’ve created two values a and b and assign number 7 to variable a, and 0 to variable b. Then using built-in function print we’ve tried to print out result of dividing variable a by b. Since we can’t divide with zero the Python gave us exception called ZeroDivisionError telling us that we can’t divide integer with zero.
Most common exceptions that you will encounter while programming are:
Index Error – a list is indexed with an out-of-range number
Name Error – an unknown variable is used
Syntax Error – the code can’t be praised properly
Type Error – a function is called on a value of an inappropriate type
Value Error – a functions is called on a value of the correct type, but with an inappropriate value.

Index Error

IndexError is type of error that you’ll encounter when a list is indexed with an out-of-range number. For now we’ll not get into details with lists. We’ll create a simple list and then try to call an a member of a list which doesn’t exist.
>>> a = [1,2,3,4,5]
>>> print a[0]
1
>>> print a[5]
Traceback (most recent call last):
File "", line 1, in 
IndexError: list index out of range
So the first element of a list is 1 with index 0, second element is 2 with index 1 and so on. We’ve tried to print out the first element and we’ve succeeded because the first element with index 0 is 1. Then we’ve tried to print out the member of list with index number 5 which doesn’t exist so we’ve got the IndexError saying that the list is out of range. For more information about the lists check out the List section of this tutorial.

 Name Error

NameError is type of exception that will result from using a variable that doesn’t exist. It’s not define previously in our program.
>>> a = 5
>>> c = a +d
Traceback (most recent call last):
  File "", line 1, in 
NameError: name 'd' is not defined
This is very simple program. We’ve defined variable a and assign a integer value of 5 to it. Then we’ve asked how much is c = a + d but the variable d is not defined. Because the variable d is not defined we’ve got Name Error saying that name ‘d’ is not defined. To correct this just define variable d and assign value to it.
>>> a = 5
>>> d = 10
>>> c = a + d
>>> print c
15


 SyntaxError

SytaxError can be result of mistyping the function you’re trying to use. For example if we’re trying to print out the word “Hello” as shown below
>>> print('Hello')*
  File "", line 1
    print('Hello')*
                 ^
SyntaxError: invalid syntax
We’ve accidentally entered the * sign so the result is SyntaxError: invalid syntax

Type Error

Type error is result of using different type variables for example string and integer variable in function print.
>>> a = 5
>>> b = 'Hello'
>>> print a + b
Traceback (most recent call last):
  File "", line 1, in 
TypeError: unsupported operand type(s) for +: 'int' and 'str'
To correct this we need to convert number 5 into string using an str function and then concatenate this two variables using + sign.
>>> a = 5
>>> b = 'Hello'
>>> print str(a) + b
5Hello

Value error

This error will happen when we’re trying to use function but with inappropriate value. For this example will try to convert variable b which is equal to word “Hello” into integer using built-in integer function called ‘int()’
>>> b = 'Hello'
>>> int(b)
Traceback (most recent call last):
  File "", line 1, in 
ValueError: invalid literal for int() with base 10: 'Hello'
The Exception occurred because we cant convert string into integer number.

 FYI: More Exceptions


The list of all exceptions that you can encounter while programming in Python are given in the following table with their description.

EXCEPTION NAME
DESCRIPTION
Exception
Base class for all exceptions
StopIteration
Raised when the next() method of an iterator does not point to any object.
SystemExit
Raised by the sys.exit() function.
StandardError
Base class for all built-in exceptions except StopIteration and SystemExit.
ArithmeticError
Base class for all errors that occur for numeric calculation.
OverflowError
Raised when a calculation exceeds maximum limit for a numeric type.
FloatingPointError
Raised when a floating point calculation fails.
ZeroDivisonError
Raised when division or modulo by zero takes place for all numeric types.
AssertionError
Raised in case of failure of the Assert statement.
AttributeError
Raised in case of failure of attribute reference or assignment.
EOFError
Raised when there is no input from either the raw_input() or input() function and the end of file is reached.
ImportError
Raised when an import statement fails.
KeyboardInterrupt
Raised when the user interrupts program execution, usually by pressing Ctrl+c.
LookupError
Base class for all lookup errors.
IndexError
KeyError
Raised when an index is not found in a sequence.
Raised when the specified key is not found in the dictionary.
NameError
Raised when an identifier is not found in the local or global namespace.
UnboundLocalError
EnvironmentError
Raised when trying to access a local variable in a function or method but no value has been assigned to it.
Base class for all exceptions that occur outside the Python environment.
IOError
IOError
Raised when an input/ output operation fails, such as the print statement or the open() function when trying to open a file that does not exist.
Raised for operating system-related errors.
SyntaxError
IndentationError
Raised when there is an error in Python syntax.
Raised when indentation is not specified properly.
SystemError
Raised when the interpreter finds an internal problem, but when this error is encountered the Python interpreter does not exit.
SystemExit
Raised when Python interpreter is quit by using the sys.exit() function. If not handled in the code, causes the interpreter to exit.
Raised when Python interpreter is quit by using the sys.exit() function. If not handled in the code, causes the interpreter to exit.
Raised when an operation or function is attempted that is invalid for the specified data type.
ValueError
Raised when the built-in function for a data type has the valid type of arguments, but the arguments have invalid values specified.
RuntimeError
Raised when a generated error does not fall into any category.
NotImplementedError
Raised when an abstract method that needs to be implemented in an inherited class is not actually implemented.

1 komentar: