exception try-catch   0   233
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.

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


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.


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 

exception try-catch   0   233

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

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

Please subscribe to get the latest articles in your mailbox.

Recent Posts:

© pythoncircle.com 2018-2019
Contact Us: code108labs [at] gmail.com
Address: 3747 Smithfield Avenue, Houston, Texas