profile for Gajendra D Ambi on Stack Exchange, a network of free, community-driven Q&A sites

Monday, November 20, 2017

Python 3.6 Handling errors and exceptions

Error handling one of the great feature of python and it offers a lot of versatility. Let us first build up the need for this feature of python.

if 1<2:
    print('Hello world'
File "<ipython-input-1-83ff31806b18>", line 2
    print('Hello world'
                       ^
SyntaxError: unexpected EOF while parsing

You will notice that the missing parenthesis causes the above error. Correcting the above just works fine.


if 1<2:
    print('Hello world')
Hello world

Let us take another example.

x = int(input("Please enter a number: "))
Please enter a number: hey
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-3-553ece37be8b> in <module>()
----> 1 x = int(input("Please enter a number: "))

ValueError: invalid literal for int() with base 10: 'hey'

Here x was expecting an integer but we gave it a string and thus we see the error above. The error above is very self explanatory. We were not prepared for this but we should be. You see that this was a ValueError.


try:
    x = int(input("Please enter a number: "))
except ValueError:
    print ('Please enter an integer')
Please enter a number: hey
Please enter an integer

We now have a way of handling the exception called ValueError. We display a message instead of the error. What if this is not enough.


try:
    x = int(input("Please enter a number: "))
    print('batman')
    y = x//0
    print('superman')
    print(y)
except ValueError:
    print ('Please enter an integer')

Please enter a number: 8
batman
---------------------------------------------------------------------------
ZeroDivisionError                         Traceback (most recent call last)
<ipython-input-1-9a959f723c86> in <module>()
      2     x = int(input("Please enter a number: "))
      3     print('batman')
----> 4     y = x//0
      5     print('superman')
      6     print(y)

ZeroDivisionError: integer division or modulo by zero

Now this is getting interesting. The code threw an error at line 4 and thus everything ran before than but nothing after that. That is the beauty of try except. On the very first exception it jumps directly to the except clause.
Here you will also see that you have another exception called ZeroDivisionError. If you are unsure of what exceptions might arise then just catch them all and display which one occurred.

try:
    x = int(input("Please enter a number: "))
    y = x//0
    print(y)
except Exception:
    print ('something went wrong')

Please enter a number: hey
something went wrong


try:
    x = int(input("Please enter a number: "))
    y = x//0
    print(y)
except Exception:
    print ('something went wrong')

Please enter a number: 8
something went wrong

Now we are just displaying something went wrong irrespective of what the exception is. Let us change that.
In the following 2 code blocks you see that the exact exception is displayed.

try:
    x = int(input("Please enter a number: "))
    y = x//0
    print(y)
except Exception as e:
    print (e)

Please enter a number: 8
integer division or modulo by zero


try:
    x = int(input("Please enter a number: "))
    y = x//0
    print(y)
except Exception as e:
    print (e)
Please enter a number: hey
invalid literal for int() with base 10: 'hey'

Let us look at the code below

try:
    x = int(input("Please enter a number: "))
    y = x//1
    print(y)
except Exception as e:
    print (e)
else:
    print('we did not encounter any exceptions')

Please enter a number: 8
8
we did not encounter any exceptions

Here we have changed the y = x//0 to y = x//1. Since we did not encounter any exceptions the else clause executed. The else clause only executes if there are no exceptions. There is however finally which gets executed at the end irrespective of all these.


try:
    x = int(input("Please enter a number: "))
    y = x//1
    print(y)
except Exception as e:
    print (e)
else:
    print('we did not encounter any exceptions')
finally:
    print('I will run no matter what and that is why I am called finally')

Please enter a number: 8
8
we did not encounter any exceptions
I will run no matter what and that is why I am called finally


try:
    x = int(input("Please enter a number: "))
    y = x//1
    print(y)
except Exception as e:
    print (e)
else:
    print('we did not encounter any exceptions')
finally:
    print('I will run no matter what and that is why I am called finally')

Please enter a number: hey
invalid literal for int() with base 10: 'hey'
I will run no matter what and that is why I am called finally

You can see that else executed when there were no exceptions but finally always gets executed. Sometimes you might want to have your own exceptions defined. You might want to check or assert for certain things and raise an exception there. Here is how we can do it.


try:
    x = int(input("Please enter a number: "))
    if x < 1:
        raise Exception
    y = x//1
    print(y)
except Exception as e:
    print ('The vallue is less than one')
else:
    print('we did not encounter any exceptions')
finally:
    print('I will run no matter what and that is why I am called finally')

Please enter a number: -1
The vallue is less than one
I will run no matter what and that is why I am called finally

clone my github here.
https://github.com/MrAmbiG/LearningPython

No comments:

Post a Comment