Exception Handling
You need to handle exception in your programme otherwise it will terminate after exception (error).
If you have any code which may cause error while execution, you need to put that code under “try” block, after the try: block, you need to include an except: block.
You can write exception handling in following ways :
1 2 3 4 5 6 |
try: fd = open("file_name", "w") fd.write("Writing in file") fd.close() except Exception,e: print "Error: %s"%e |
Try block will start executing, if there will any error while file handling then it will go to except block else it will not go to except block.
We can write above programme in more relevant using try… except.. else.. block.
Else block executes only when there is no error in try block.
1 2 3 4 5 6 7 |
try: fd = open("file_name", "w") except Exception,e: print "Error: %s"%e else: fd.write("Writing in file") fd.close() |
We can write same programme using finally block also, if there is any error while writing into the file.
finally block will always execute, doesn’t matter whether error occurred in try block or not.
1 2 3 4 5 6 7 |
try: fd = open("file_name", "w") fd.write("Writing in file") except Exception,e: print "Error: %s"%e finally: fd.close() |