How to Raise Exception in Python

Python provides robust error handling features to catch errors and take action without stopping the program execution. In this article, we will look at how to raise exception in Python using try-except statements.


How to Raise Exception in Python

Python provides many exceptions that are automatically raised by its interpreter whenever there is an error in your program. When such errors occur, python stops the execution of program and returns control to the calling function, unless it is handled. If the exception is not handled, then your program will display an error message and stop executing further.

Although Python interpreter automatically raises exceptions whenever there is an error in your program, you can also manually raise exceptions, using raise keyword followed by the type of Exception.

Here are a couple of examples to raise exception in Python.

>>> raise KeyboardException
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'KeyboardException' is not defined
>>> raise MemoryError("This is an argument")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
MemoryError: This is an argument

Also read : How to Install PHPMyAdmin in Ubuntu


Catch Exceptions in Python

Now we will see how to catch these exceptions raised by Python. If they are not caught and handled, then your program will give an error and stop working.

You can catch an exception in Python using try …except statement. Here is an example of function that catches an exception.

>>> def test(i):
         try:
             a=1/i
             print a
         except:
              print "cannot divide a number by zero"
>>> test(1)
1
>>> test(0)
cannot divide a number by zero

The above function takes a parameter and divides 1 by that number. If we input 0 in that function, python would raise an exception since any number of divided by zero is not defined.

We use use a try statement at the beginning of our function, and except statement to catch the statement and return a meaningful error message.

Also read : How to Install MongoDB in Ubuntu

Whenever there is an exception, Python also generates its own error message which are helpful most of times. If you want to capture and display these system generated error messages, then modify the except statement to use Exception object as shown below.

>>> def test(i):
        try:
             a=1/i
             print a
        except Exception as e:
              print e.message
>>> test(1)
1
>>> test(0)
integer division or modulo by zero

Also read : How to Use cURL to download files in Python

In fact, you can assign different except statements to catch different types of errors.

Here is an example.

try:
   # do something
   pass

except (TypeError, ZeroDivisionError):
   # handle multiple exceptions
   # TypeError and ZeroDivisionError
   pass

except ValueError:
   # handle ValueError exception
   pass

except:
   # handle all other exceptions
   pass

As you can see Python provides a robust Exception management feature that is very useful in application development.

Also read : How to Extract data form JSON in Python