Python tutorial- Errors handling


Errors handling


In writing computer programs, you might face a lot of errors. Although some errors are not bad things, the users who use your software may feel that it is not good software and will not use it any more. Therefore, it is import that you know how to handle those errors.
Using try...except to catch errors
Python provides try…except block to handle errors. Please consider the following situation. We create a function(mul) to multiply 2 integer values. If the user does not input the integer numbers (they input strings instead), you programs will crash.
 
>>> def mul(x,y):
            return x*y
 
>>> mul('x','y')
 
Traceback (most recent call last):
  File "<pyshell#8>", line 1, in <module>
    mul('x','y')
  File "<pyshell#7>", line 2, in mul
    return x*y
TypeError: can't multiply sequence by non-int of type 'str'
>>> 
 
Let try to use try…except block to catch the error.
>>> def mul(x,y):
                        try:
                                    return x*y
                        except TypeError:print 'Invalid input'
 
                       
>>> mul('x','y')
Invalid input
>> 
Now, the error is handled. The program produces a friendly message ‘Invalid input’ when the user supply the wrong types of parameters.
 
The table below describes some of built-in exception classes you should know.
 
Class Description
AttributeError Raised when attribute is not found
Exception The common base class for all exceptions
IndexError Raised when sequence index is out of range
IOError Raised when trying to open a nonexistent file (among other things)
KeyError Raised when using a nonexistent key on a mapping
NameError Raised when a name (variable) is not found
SyntaxError Raised when there is invalid syntax in your code
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 an inappropriate value (correct type)
ZeroDivisionError Raised when the second argument of a division or modulo operation is zero

 
Example 1: Handling attributes error
>>> from Python_source import MultTable
>>> MultTable.getTable()
 
Traceback (most recent call last):
  File "<pyshell#20>", line 1, in <module>
    MultTable.getTable()
AttributeError: 'module' object has no attribute 'getTable'
>>> 
The error is raised because the function name getTable() doesn’t exist in the current module. So, you need to use AttributeError class to handle it.
>>> try:
            MultTable.getTable()
except AttributeError:print 'The function does not exist.'
 
The function does not exist.
>> 
Example 2: Handling index error
>>> lst=range(1,10)
>>> lst[11]
 
Traceback (most recent call last):
  File "<pyshell#29>", line 1, in <module>
    lst[11]
IndexError: list index out of range
>>> 
If the user tries to access the element of a list by index which does not exist in the list, index error will be raised. To handle it, use IndexError class.
>>> try:
            lst[11]
except IndexError:'Print the index specified does not exist.'
 
'Print the index specified does not exist.'
>>> 
 
Example 3: Handling key error
 
>>> Dic={1:'Pizza',2:'Fried Chicken',3:'Hamburger'}
>>> Dic[4]
 
Traceback (most recent call last):
  File "<pyshell#37>", line 1, in <module>
    Dic[4]
KeyError: 4
>>> 
The key 4 doesn’t exist. It is a type of key error. Therefore, KeyError class needs to be used.
>>> try:
            Dic[4]
except KeyError:print 'The specified key does not exist.'
 
The specified key does not exist.
>>> 
 
Example 4: Handling zero division error
>>> y=10/0
 
Traceback (most recent call last):
  File "<pyshell#44>", line 1, in <module>
    y=10/0
ZeroDivisionError: integer division or modulo by zero
>>> 
The zero division error can be caught by using ZeroDivisionError class.
 
>>> try:
            y=10/0
except ZeroDivisionError:'Print the dividor can not be zero.'
 
'Print the dividor can not be zero.' >>> 


Comments




This website intents to provide free and high quality tutorials, examples, exercises and solutions, questions and answers of programming and scripting languages:
C, C++, C#, Java, VB.NET, Python, VBA,PHP & Mysql, SQL, JSP, ASP.NET,HTML, CSS, JQuery, JavaScript and other applications such as MS Excel, MS Access, and MS Word. However, we don't guarantee all things of the web are accurate. If you find any error, please report it then we will take actions to correct it as soon as possible.