DEV Community

Cover image for try .. except .. else .. in python with example
Anurag Rana
Anurag Rana

Posted on • Originally published at pythoncircle.com

Try Except Else try .. except .. else .. in python with example

This post was originally published on PythonCircle.com

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
>>> 
Enter fullscreen mode Exit fullscreen mode

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
>>> 
Enter fullscreen mode Exit fullscreen mode

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
>>> 
Enter fullscreen mode Exit fullscreen mode

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()
...
Enter fullscreen mode Exit fullscreen mode

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
>>> 
Enter fullscreen mode Exit fullscreen mode

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')
Enter fullscreen mode Exit fullscreen mode

Output:

file was opened
going to close file
exception in number conversion
Enter fullscreen mode Exit fullscreen mode

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

This post was originally published on PythonCircle.com

More from Author:

Top comments (0)