try .. except .. else .. in python with example

You will face at least two types of errors while coding with python. Syntax errors and exceptions.

Syntax errors are also known as parsing errors. Compiler informs us about the parsing errors using an arrow.


rana@brahma:~$ python3
Python 3.5.2 (default, Nov 12 2018, 13:43:14) 
[GCC 5.4.0 20160609] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> while True print("Hello")
  File "<stdin>", line 1
    while True print("Hello")
                   ^
SyntaxError: invalid syntax
>>> 


Even when your code is perfect syntax wise, some lines may report an errors when you try to execute them. Errors reported at runtime are known as exceptions.

For an uninterrupted execution, we must handle the exceptions properly. We can do so by using try except block. 

In below example we are trying to add a string and an integer. When statement is executed it throws an exception. 

>>> a = 'rana' + 10
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: Can't convert 'int' object to str implicitly
>>> 


If we don't handle this exception, program will exit abruplty. Handle the exception using try except statements.


>>> 
>>> try:
...     a = 'rana' + 10
... except Exception as e:
...     print('Some useful message to debug the code')
... 
Some useful message to debug the code
>>> 

When above piece of code is executed, exception is thrown but is then catched by except block which in turn print a useful message which helps in debugging the code.


try ... except statement have an optional else clause. Else part is executed when there is no exception thrown in try clause. Else part is executed before finally clause.

Lets say you are trying to open a file in try block (just an example) and it is possible there might occur some error in opening the file, we will handle exception in except block. If there is no exception thrown, file is opened successfully, we have to close the file descriptor. 


>>> try:
...     f = open('filename.txt','r')
... except Exception as e:
...     print('Some exception in opening the file')
... else:
...     f.close()
...


Its better to add code to else clause instead of adding code to try clause. This helps in avoiding catching the exception which was not raised by code being protected in try caluse. For example in addition to opening file in try clause, we were also trying to convert a variable to integer. Imaging file opened just fine but convertion to int threw an exception which will be reported by except block as exception in opening file, which will be misleading. See the example code below.


>>> try:
...     f = open('filename.txt','r')
...     a = 'five'
...     b = int(a)
... except Exception as e:
...     print('can not open file')
... else:
...     f.close()
... 
can not open file
>>> 
 

Above could should be rewritten as below.

try:
    f = open('filename.txt','r')
    print('file was opened')
except Exception as e:
    print('can not open file')
else:
    print('going to close file')
    f.close()
try:
    a = 'five'
    b = int(a)
except Exception as e:
    print('exception in number conversion')

Output:

file was opened
going to close file
exception in number conversion

This make sure that actual exception is reported by except clause.


Now question arises, if we should use except or else block to control the execution flow?

In python using exception to control the execution flow is normal. For example iterators uses stopIteration exception to singal the end of items.

You can read more about exceptions by visitng the links in reference section below.

References:

1. https://stackoverflow.com/questions/16138232/is-it-a-good-practice-to-use-try-except-else-in-python
2. https://docs.python.org/3/tutorial/errors.html

Image source: quotemaster.org 




Related Articles:
Python Script 3: Validate, format and Beautify JSON string Using Python
Validating json using python code, format and beautify json file using python, validate json file using python, how to validate, format and beautify json...
Encryption-Decryption in Python Django
How to encrypt and decrypt the content in DJango. Encrypting the critical information in Django App. Encrypting username, email and password in Django...
Adding Robots.txt file to Django Application
Adding robots.txt file in your Django application. Easiest way to add robots.txt file. Django application robots.txt file. Why should you add robots.txt file in your Django Application....
Scraping 10000 tweets in 60 seconds using celery, RabbitMQ and Docker cluster with rotating proxy
Scrapping large amount of tweets within minutes using celery, RabbitMQ and docker cluster. Scraping huge data quickly using docker cluster with TOR....

0 thoughts on 'Try .. Except .. Else .. In Python With Example'
Leave a comment:


*All Fields are mandatory. **Email Id will not be published publicly.


SUBSCRIBE
Please subscribe to get the latest articles in your mailbox.



Recent Posts:






© pythoncircle.com 2018-2019