PYTHON PROGRAMMING EXERCISES 7: EXCEPTION HANDLING

in STEMGeeks2 months ago

Exceptions are the unexpected events that happen during the execution of our program and that may halt the execution of our program or even cause the program to crash. In python, exception handling can be easily achieved with short code and simple logic. The use of try-except block can help us to achieve the exception handling. The try block allows us to test the code that cause the exception and the except block allows us to handle the corresponding exception. By using this, we can display user friendly messages to the users to let them know about the errors.

One of the most common example of exception handling in every programming language is dividing a number by zero. Lets try to do the same in python.

If you try to run this simple code: print(10/0) in python, it will throw us the following error message during runtime.

Screenshot_1.png

Python really has a very cool features that will help us to debug the exception. You can see in the Traceback the line number which caused the exception and it also specifies the type of exception which is ZeroDivisionError in this case. Also if you don't handle this type of exception in a large enterprise project, a hacker can get idea of how to hack into your program just by looking into that Traceback.

Now lets use try-except block to show user friendly message. I have just mentioned above how to use try-except block.

try:
    print(10 / 0)
except ZeroDivisionError:
    print("Dividing a number by 0 is not possible.")

Executing this code will give you following output:

image.png

Now I will show you some disadvantages of this approach and how python will allow us to remove this one. Lets say I have other statements to run inside try block.

try:
    print("Program Initiated")
    print(10 / 2)
    print("Program Closed.")
except ZeroDivisionError:
    print("Dividing a number by 0 is not possible.")

There is no exception at this point. You will get the following output:

image.png

But lets change the print statement to be divided by 0.

try:
    print("Program Initiated")
    print(10 / 0)
    print("Program Closed.")
except ZeroDivisionError:
    print("Dividing a number by 0 is not possible.")

If you run this code, the output will be as below:

image.png

See as soon as the error was found in the try block, it automatically jumps out of the try statement without even executing the rest code which is Program Closed in our case. It went to except block as soon as it encounters the error and that block gets executed. In your large enterprise project, there is always some code that needs to be executed even after the exception is found. One approach to this one is that you can Print Program Closed in except block but thats not a nice approach as it gets printed only if error is encountered. We want to print that whether or not the error is found.

So we have one keyword called finally that will help to execute a code no matter if statement inside try gets executed or statement inside except gets executed. Lets use this one for above scenario.

try:
    print("Program Initiated")
    print(10 / 0)
except ZeroDivisionError:
    print("Dividing a number by 0 is not possible.")

finally:
    print("Program Closed.")

If you run this code, the output is:

image.png

Now lets change our print statement so that error is not encountered.

try:
    print("Program Initiated")
    print(10 / 2)
except ZeroDivisionError:
    print("Dividing a number by 0 is not possible.")

finally:
    print("Program Closed.")

The output is:

image.png

In this way you can handle the exception in Python. There are many other types of exception that you can handle using try-block and finally like FileNotFoundError which is raised when the program can't find the specified file. You can use access mode like reading, writing, appending, deleting only if file is found.

You can check and run this code online here.

Sort:  

Manually curated by EwkaW from the @qurator Team. Keep up the good work!

Thanks @ewkaw and qurator team for support. You guys are awesome🙂

You're very welcome :D

Man, it's nice to see a programming post on this platform, I was searching for those, but almost every post is old. Keep going sir!!

Thanks Paulo🙂. This type of comments keeps me going here. Appreciate it.