• +1-617-874-1011 (US)
  • +44-117-230-1145 (UK)
Live Chat
Follow Us:

Exception handling in Python Programming

In this tutorial, we shall be looking at what is exception handling, how do we deal with it in Python.

Let us first understand that what is an exception.

As the name suggests that “Exception” is something that is not expected, and you do not have any control over it. You cannot stop an exception from occurring but you can prevent it from causing any damage to your programming by telling the interpreter what to do when it encounters the exception. Like when you are not sure about the weather but you still carry an umbrella with you and then after sometime, it starts raining. While others are having a rain shower, you are safe with your umbrella. Same is with an exception in programming, if you tell it what to do in case of any exception, then you are safe else it will harm you.

Let us look at some types of exceptions that are there in Python.

1. Exception

2. StopIteration

3. SystemExit

4. StandardError

5. ArithmeticError

6. OverflowError

7. FloatingPointError

8. ZeroDivisionError

9. AssertionError

10. AttributeError

11. EOFError

12. ImportError

13. KeyboardInterrupt

14. LookupError

15. IndexError

16. KeyError

17. NameError

18. UnboundLocalError

19. EnvironmentError

20. IOError

21. SyntaxError

22. IndentationError

23. SystemError

24. SystemExit

25. TypeError

26. ValueError

27. RuntimeError

28. NotImplementedError

Let us now see that how we can write a code to handle exception.

There are 3 blocks

a) The try block -> here, we write the code that is, what we want to execute.

b) The except block -> here, we write that what error can be encountered and then we will write the print statement regarding the exception.

c) The else block -> here, we write what we want to execute or print, in case there is no error.

Let us look at an example to get a better understanding.

		try:
		   p = open("amazing", "w")
		   p.write("Python is an amazing language and i love it!!")
		except IOError:
		   print ("Error: can\'t find file or read data")
		else:
		   print ("successfully written in the file")
		   p.close()

Output:

successfully written in the file

let us try the same example with an exception.

		try:
		   p = open("amazing", "r")
		   p.write("Python is an amazing language and i love it!!")
		except IOError:
		   print ("Error: file not found or unable to read data")
		else:
		   print ("successfully written in the file")
		   p.close()

Output:

Error: file not found or unable to read data

Let us create a function in which we use exception handling.

		def top(value):
			   try:
				  return float(value)
			   except ValueError:
				  print ("The argument is not of float-type\n")


		top('pru')

Output:

The argument is not of float-type

Since we have passed a string value and we are checking for a float value therefore, we are getting an exception in which we are printing a statement.

Then we are calling the function passing an argument and getting an exception.

This is it for this tutorial, I hope that that you are pretty much clear about the concept of exception and how to handle it. You can try it out yourself and test your knowledge.

Summary

In these tutorials, we talked about Python, its scope, what are its some of its uses.

We learned about its syntax, how to get started how to install python on your system etc. Then we learnt about loops, what kinds of loops are there in python for loop and while loop, their uses and how can we write them in our programs.

Then we looked onto functions, what are functions, then we created our own functions and learnt their functionalities. Then we came across the if and else statements and used them for doing some tasks.

We also learnt about different types of operators that are, conditional, logical, arithmetic etc. and looked at their working.

Then we learnt about some pre-defined Python functions that we can use to reduce our overhead that is the function will perform the activity and we just need to call it for the execution.

Then we learned about modules, what are modules, its uses and how can we create our own module. By importing the modules, we can use their functionalities or all the functions that are defined in the module with the help of “*” asterisk.

Then we came across file handling, how can we create a file, read the file, write in the file or perform both the operations. Learnt about the different modes to open a file.

Then we learnt about exceptions, what are exceptions, how can we create an exception or handle one with the help of expect statement and the else statement.

We pretty much tried to cover a vast variety of topics that were the part of the basics of Python. And after reading or going through the tutorials, I am sure that now you have the intermediate level knowledge of Python. Incase of any doubt, you can go through the tutorials once again.

I hope that you were able to learn something from this tutorial and it was helpful for you in any way.

------------------------------------------------------------------------------------------------------