try and except in Python

PythonServer Side ProgrammingProgramming

To use exception handling in python, we first need to catch the all except clauses.

Python provides, “try” and “except” keywords to catch exceptions. The “try” block code will be executed statement by statement. However, if an exception occurs, the remaining “try” code will not be executed and the except clause will be executed.


Let’s see above syntax with a very simple example −

 Live Demo

   print("Hello, World!")
   print("This is an error message!")


Hello, World!

Above is a very simple example, let’s understand the above concept with another example −

 Live Demo

import sys
List = ['abc', 0, 2, 4]
for item in List:
      print("The List Item is", item)
      r = 1/int(item)
   print("Next Item from the List is: ")
print("The reciprocal of",item,"is",r)


The List Item is abc
Oops! <class 'ValueError'> occured.
Next Item from the List is:
The List Item is 0
Oops! <class 'ZeroDivisionError'> occured.
Next Item from the List is:
The List Item is 2
The reciprocal of 2 is 0.5

In the above program, the loops run until we get (as user input) an integer that has a valid reciprocal. The code which causes an exception to raise is placed within the try block.

In case some exception occurs, it will be caught by the except block. We can test the above program with different exception errors. Below are some of the common exception errors −

  • IOError

    Raised in case we cannot open the file.

  • ImportError

    Raised in case module is missing.

  • ValueError

    It happened whenever we pass the argument with the correct type but an inappropriate value of a built-in operator or function.

  • KeyboardInterrupt

    Whenever the user hits the interrupt key (generally control-c)

  • EOFError

    Exception raised when the built-in functions hit an end-of-file condition (EOF) without reading any data.

Published on 19-Feb-2019 16:52:43