dzone python training institute in jaipur

Exception Handling in Python

Here in this blog, you will learn that how Python handles run time errors means exceptions? But before proceeding further lets laid down some focus on what is exception handling, why to use it and when an exception is raised.

What is an Exception?

When an error occurs during the execution of a program then it is known as exception. when any error occurs at run time, the exception is generated by Python to save the program from crash.

Why use exceptions handling?

As run time errors terminate the program execution and abnormally shut down the software so it is must to caught run time errors for smooth execution of program or software.

When exception is raised?

Whenever in your code there is an error due unavailability of any resources , memory or misleading an exception is thrown by system, which has to be caught within the code to avoid shutdown of program.

How to raise an exception manually?

By using the raise exception statement, you can easily raise an exception in your running program. By raising an exception, it breaks the current codes and returns the exception back till it get sorted.

List of exception Classes

				
IOError
If the file cannot be opened.

ImportError
If python cannot find the module

ValueError
Raised when a built-in operation or function receives an argument that has the
right type but an inappropriate value

KeyboardInterrupt
Raised when the user hits the interrupt key (normally Control-C or Delete)

EOFError
Raised when one of the built-in functions (input() or raw_input()) hits an
end-of-file condition (EOF) without reading any data

How to handle an exception?

If you find any suspicious code that can raise an exception, then you can protect your program by placing a suspicious code in a try: block. After this block, the except: statement handles the program in an efficient manner.

				
Syntax
try:
	Perform your operations here;
......................
except Exception1:
	jump in this section on a particular exception
except Exception2:
	Jump in this section on a particular exception
else:
   If there is no exception then execute this block.
   				
				

Some Important points for the above-mentioned syntax

  • In the single try statement, you can add multiple except statements. this is fruitful only when the try block contains statement that may raise different types of exceptions.
  • To handle any exception, you can provide a generic except clause.
  • After adding the except clause(s), you can add else-clause if needed. This is required only when the try: block does not raise an exception.
  • The else-block is a good place for code of successful implementation message and it does not required the try: block's protection.
				
Example:
try:
   fh = open("test", "r")
   fh.write("File Opened in try block!!")
except IOError:
   print "Sorry Unable to open file or write"
else:
   print "the content has been successfully written in the file" 
   
   

Try-finally clause

The finally: block can be used along with try: block. In the finally: block you can put any code that you want must to be executed, whether the try: block raises an exception or not.

				
Example:-
try:
   fh = open("test", "w")
   fh.write("My test file to handle exception!!")
finally:
   print "Error: Unable to open file or read data"