create account

PYTHON PROGRAMMING EXERCISES 7: EXCEPTION HANDLING by leoumesh

View this thread on: hive.blogpeakd.comecency.com
· @leoumesh ·
$17.47
PYTHON PROGRAMMING EXERCISES 7: EXCEPTION HANDLING
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](https://files.peakd.com/file/peakd-hive/leoumesh/23tbLvbt28bEbvYExyMVMa5DY3Yvi4KdYpskGpc9SHmd1Cr8BQCxvrLEzgztQJ4NTBTd6.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](https://files.peakd.com/file/peakd-hive/leoumesh/23t79KyDENRTDr3o4gFtkaMJnCrTYTVsZchMtzdMthzuaScSG7mP2xBqteYPDcWJ81UN8.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](https://files.peakd.com/file/peakd-hive/leoumesh/23t797udeSextrEFSDjsY9qiGhpw6MJLbtTxiSZhMSa87bFVV3EhswaytV2BVaVySoDGG.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](https://files.peakd.com/file/peakd-hive/leoumesh/23t79F6NV1ALKhpD93yXvaDo7Lm88s5ot4LGvFVNNppBGP5G8tYkZbnaPCD4novqCNRHn.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](https://files.peakd.com/file/peakd-hive/leoumesh/23t797uH7KU3K4aFu4PNfb2o5osruVU9qTwTGqEeCMxVsNqHDBciVN1SkpoQDb3988dZE.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](https://files.peakd.com/file/peakd-hive/leoumesh/Eo1wRwoyjP2anSNuKqdkDUVKuijVcbffrkEheWKSMDWGxS5y95f166shNctw4WhxzsN.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](https://www.onlinegdb.com/online_python_compiler). 
👍  , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , and 171 others
properties (23)
authorleoumesh
permlinkpython-programming-exercises-7-exception-handling
categoryhive-163521
json_metadata"{"app":"peakd/2021.04.4","format":"markdown","description":"Tutorial on how to handle exception in Python","tags":["python","programming","code","coding","tutorial","exception","handling","pycharm","exercises","stem"],"image":["https://files.peakd.com/file/peakd-hive/leoumesh/23tbLvbt28bEbvYExyMVMa5DY3Yvi4KdYpskGpc9SHmd1Cr8BQCxvrLEzgztQJ4NTBTd6.png","https://files.peakd.com/file/peakd-hive/leoumesh/23t79KyDENRTDr3o4gFtkaMJnCrTYTVsZchMtzdMthzuaScSG7mP2xBqteYPDcWJ81UN8.png","https://files.peakd.com/file/peakd-hive/leoumesh/23t797udeSextrEFSDjsY9qiGhpw6MJLbtTxiSZhMSa87bFVV3EhswaytV2BVaVySoDGG.png","https://files.peakd.com/file/peakd-hive/leoumesh/23t79F6NV1ALKhpD93yXvaDo7Lm88s5ot4LGvFVNNppBGP5G8tYkZbnaPCD4novqCNRHn.png","https://files.peakd.com/file/peakd-hive/leoumesh/23t797uH7KU3K4aFu4PNfb2o5osruVU9qTwTGqEeCMxVsNqHDBciVN1SkpoQDb3988dZE.png","https://files.peakd.com/file/peakd-hive/leoumesh/Eo1wRwoyjP2anSNuKqdkDUVKuijVcbffrkEheWKSMDWGxS5y95f166shNctw4WhxzsN.png"]}"
created2021-04-29 10:20:00
last_update2021-04-29 10:20:00
depth0
children5
last_payout2021-05-06 10:20:00
cashout_time1969-12-31 23:59:59
total_payout_value9.579 HBD
curator_payout_value7.888 HBD
pending_payout_value0.000 HBD
promoted0.000 HBD
body_length4,810
author_reputation212,340,493,251,438
root_title"PYTHON PROGRAMMING EXERCISES 7: EXCEPTION HANDLING"
beneficiaries[]
max_accepted_payout1,000,000.000 HBD
percent_hbd0
post_id103,370,550
net_rshares19,462,378,813,707
author_curate_reward""
vote details (235)
@paulo.sar ·
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!!
properties (22)
authorpaulo.sar
permlinkre-leoumesh-qsez6c
categoryhive-163521
json_metadata{"tags":["hive-163521"],"app":"peakd/2021.04.4"}
created2021-05-01 05:56:36
last_update2021-05-01 05:56:36
depth1
children1
last_payout2021-05-08 05:56:36
cashout_time1969-12-31 23:59:59
total_payout_value0.000 HBD
curator_payout_value0.000 HBD
pending_payout_value0.000 HBD
promoted0.000 HBD
body_length132
author_reputation2,642,211,824,482
root_title"PYTHON PROGRAMMING EXERCISES 7: EXCEPTION HANDLING"
beneficiaries[]
max_accepted_payout1,000,000.000 HBD
percent_hbd10,000
post_id103,407,563
net_rshares0
@leoumesh ·
Thanks Paulo🙂. This type of comments keeps me going here. Appreciate it.
👍  
properties (23)
authorleoumesh
permlinkqshkf2
categoryhive-163521
json_metadata{"app":"hiveblog/0.1"}
created2021-05-02 15:29:48
last_update2021-05-02 15:29:48
depth2
children0
last_payout2021-05-09 15:29:48
cashout_time1969-12-31 23:59:59
total_payout_value0.000 HBD
curator_payout_value0.000 HBD
pending_payout_value0.000 HBD
promoted0.000 HBD
body_length72
author_reputation212,340,493,251,438
root_title"PYTHON PROGRAMMING EXERCISES 7: EXCEPTION HANDLING"
beneficiaries[]
max_accepted_payout1,000,000.000 HBD
percent_hbd0
post_id103,436,631
net_rshares2,447,042,980
author_curate_reward""
vote details (1)
@qurator ·
Qurator
<center>Manually curated by EwkaW from the @qurator Team. Keep up the good work!</center>
properties (22)
authorqurator
permlink1,619,693,063
categoryhive-163521
json_metadata{"app":"Discord"}
created2021-04-29 10:44:24
last_update2021-04-29 10:44:24
depth1
children2
last_payout2021-05-06 10:44:24
cashout_time1969-12-31 23:59:59
total_payout_value0.000 HBD
curator_payout_value0.000 HBD
pending_payout_value0.000 HBD
promoted0.000 HBD
body_length89
author_reputation1,640,068,258,497,071
root_title"PYTHON PROGRAMMING EXERCISES 7: EXCEPTION HANDLING"
beneficiaries[]
max_accepted_payout1,000,000.000 HBD
percent_hbd10,000
post_id103,370,794
net_rshares0
@leoumesh ·
Thanks @ewkaw and qurator team for support. You guys are awesome🙂
properties (22)
authorleoumesh
permlinkqsbnuj
categoryhive-163521
json_metadata{"users":["ewkaw"],"app":"hiveblog/0.1"}
created2021-04-29 10:58:18
last_update2021-04-29 10:58:18
depth2
children1
last_payout2021-05-06 10:58:18
cashout_time1969-12-31 23:59:59
total_payout_value0.000 HBD
curator_payout_value0.000 HBD
pending_payout_value0.000 HBD
promoted0.000 HBD
body_length65
author_reputation212,340,493,251,438
root_title"PYTHON PROGRAMMING EXERCISES 7: EXCEPTION HANDLING"
beneficiaries[]
max_accepted_payout1,000,000.000 HBD
percent_hbd0
post_id103,370,934
net_rshares0
@ewkaw ·
You're very welcome :D
properties (22)
authorewkaw
permlinkqsbnuf
categoryhive-163521
json_metadata{"app":"hiveblog/0.1"}
created2021-04-29 10:59:03
last_update2021-04-29 10:59:03
depth3
children0
last_payout2021-05-06 10:59:03
cashout_time1969-12-31 23:59:59
total_payout_value0.000 HBD
curator_payout_value0.000 HBD
pending_payout_value0.000 HBD
promoted0.000 HBD
body_length22
author_reputation1,161,900,624,318,940
root_title"PYTHON PROGRAMMING EXERCISES 7: EXCEPTION HANDLING"
beneficiaries[]
max_accepted_payout1,000,000.000 HBD
percent_hbd10,000
post_id103,370,944
net_rshares0