Blog available for sell
This blog is available for sale. Please 'contact us' if interested.
Advertise with us
exception try-catch   1   11636
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 error 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 the 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, the program will exit abruptly. 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 the above piece of code is executed, an exception is thrown but is then caught 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.

Let's 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, the 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()
...


It's 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 an integer. Imaging file opened just fine but conversion to int threw an exception which will be reported by except block as an 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 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 makes sure that actual exception is reported by except clause.


Now the 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 use stopIteration exception to signal the end of items.

You can read more about exceptions by visiting the links in the 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 



exception try-catch   1   11636
1 comment on 'Try .. Except .. Else .. In Python With Example'
Login to comment

Tuga July 26, 2019, 5:03 a.m.
Use with to open files and you don't have to explicitly close them.
DigitalOcean Referral Badge

© 2024-2025 Python Circle   Contact   Sponsor   Archive   Sitemap