try and except in Python


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.

try:
   some_statements_here
except:
   exception_handling

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

 Live Demo

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

Output

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:
   try:
      print("The List Item is", item)
      r = 1/int(item)
      break
   except:
   print("Oops!",sys.exc_info()[0],"occured.")
   print('\n')
   print("Next Item from the List is: ")
   print()
print("The reciprocal of",item,"is",r)

Output

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.

karthikeya Boyini
karthikeya Boyini

I love programming (: That's all I know

Updated on: 30-Jul-2019

700 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements