Exception handling is so much important in programming. Suppose you are developing a project or you are running a block of code, and if some error comes the program will halt the execution and the remaining code will not execute. This can break your code and won’t give you the desired result.
So even if you found any error in your code and you want to execute the further code, then you have to use the exception handling.it provides the facility to execute the further code and also give you the error that code is encountering.
Now we will see how it provide the facility. Before moving to the examples lets see some of the common exceptions given by the python program.
- NameError: when an identifier is not found local or global.
- ZeroDivisionError: when a number is divided by zero.
- IndentationError: when code is not properly indented.
- EOFError: it occurs when everything is written in the file but still the file is open
- IOError: when an input/ output operation fails
Exception handling Method:
Example of except: i=1 j=0 try: k=i/j print(k) except: print("Exception") print("hello work is going on")
Finally: finally block always run whether there is an error in the code or not
i=1 j=0 try: k=i/j print(k) except: print("Exception") finally: print("Welcome") output: Exception Welcome
now we will see another program to understand the finally block
file=open('D:/Ram Krishna/testing.txt','w') try: name='ram' k=10/0 s=str(k) file.write(name,k) except Exception as ex: print(ex) finally: file.close() print(file.closed)
As we know file. close return true if the file is closed otherwise it will return false. if the exception will occur and we will not use the finally block than file will not be closed. but if we used the finally block then for sure the finally block will run and we will close the file in finally block will run at last
That’s it Folks on this topic. Let us know your comments on this article in the comment box below. Kindly like our facebook page, follows us on twitter and subscribe to our YouTube channel for latest updates.