Published: Aug. 15, 2019 by lukemakin |  estimated reading time: 13 minutes
Python code stops running immediately after it occures an error. To be more specific - what prevents the code from further execution is either a SyntaxError or an Exception. In this article we will explore the topic of handling errors to make your code 

reliable and error free. Errors caused by not keeping the proper format required by the Python language are Syntax Errors. See the examples below:

print "hello"

'''
Not working in python 3
the format isn't correct so a SyntaxError is given:

File "<ipython-input-78-2a0eaa89f43f>", line 1
print "hello"
^
SyntaxError: Missing parentheses in call to 'print'. Did you mean print("hello")?
'''


def my_function:
print("this is my function")

'''
Missing parenthesis after "my_function":

File "<ipython-input-79-8a00fedf7ead>", line 1
def my_function:
^
SyntaxError: invalid syntax

'''

On the other hand we have several exceptions which inherit form BaseException class and occur even if the code is written correctly (in the right format).

The problem is if, when running the program, it encounters an obstacle that actually causes an exception. Let's take a glance at some of the most popular ones with examples:

var1 = 5
var2 = "test"

print(var3)

'''
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
<ipython-input-25-b5880a42db53> in <module>
----> 1 print(var1)

NameError: name 'var1' is not defined
'''

First on our list is NameError. It occurs when variable isn't assigned like in the example above var3, which isn't defined and throws and NameError. Let's move forward to the next example:


int("Hello World")

'''
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-29-49d215ab55b5> in <module>
----> 1 int("Hello Wolrd")

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

ValueError occurs when a built-in function receives an argument with an inappropriate value. In our case, we tried to convert "Hello World" into integer which is unenforceable. Next let's learn more about TypeError:


def substract_values(a,b):
return a-b

substract_values(2, 'a')

'''
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-32-9d4c349446ff> in <module>
2 return a-b
3
----> 4 substract_values(2, 'a')

<ipython-input-32-9d4c349446ff> in substract_values(a, b)
1 def substract_values(a,b):
----> 2 return a-b
3
4 substract_values(2, 'a')

TypeError: unsupported operand type(s) for -: 'int' and 'str'
'''

TypeError is thrown when a function is applied to the wrong type of data. In this example we tried to substract from to 'a' which again - is unenforceable. Next on the list is KeyError:


my_dictionary = {
'name': 'John',
'city': 'London',
'hobby': 'sports'
}

my_dictionary['age']

'''
---------------------------------------------------------------------------
KeyError Traceback (most recent call last)
<ipython-input-34-8f58e8f1ada5> in <module>
5 }
6
----> 7 my_dictionary['age']

KeyError: 'age'
'''

KeyError occurs when a dictionary does not have a particular key. In our case we tried to get out of the dictionary the age which wasn't defined. Let's check the next one:


a = 5
b = 0

result = a/b

'''
---------------------------------------------------------------------------
ZeroDivisionError Traceback (most recent call last)
<ipython-input-35-73b18c878608> in <module>
2 b = 0
3
----> 4 result = a/b

ZeroDivisionError: division by zero
'''

ZeroDivisionError is obvious - you can't divide by zero and when you do, you get an error. The last exception we are going to cover is AttributeError:


p = 'test text'

p.add

'''
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
<ipython-input-36-1548451cfbd1> in <module>
1 p = 'test text'
2
----> 3 p.add()

AttributeError: 'str' object has no attribute 'add'
'''

AttributeError occurs when a variable doesn't have a particular atrribute (in our case 'p' doesn't have 'add'). Important to know, is that you can create custom errors with the use of 'raise'. Let's look at the example below:


def test_function(a,b,c):
if a <= b:
raise ValueError("First value must be greater than the second")
else:
return (a-b) * c

test_function(4, 9, 2)

In this case 'a' must be always greater than 'b', otherwise we'll get an error. Ok, so we discussed types of errors and how to raise a custom one. Now let's take try-catch-else-finally blocks to handle the exceptions:


def simple_function(a,b):
try:
result = a+b
except TypeError:
result = None
print("Invalid input/-s")
except:
print("Something went wrong...")
else:
print("Processed successfully")
finally:
print("Thank you")
return result


simple_function('a', 5)

'Try' allows us to test the content inside of the block. If the test fails, we can specify a general exception or even several exceptions depending on the type of error. 'Else' block is excecuted only when the 'try' block encounters no errors. We can also describe a 'finally' block that will work regardless of whether an error occurs in the function or not. Let's look at two examples of running the function above. First one is with a failed try block:


simple_function('a', 5)

'''
Invalid input/-s
Thank you
'''

Now let's take a look at a scenario where the try block is a success:


simple_function(5, 5)

'''
Processed successfully
Thank you
10
'''

In this article we covered errors and error handling. We discussed the difference between syntax errors and exceptions. Also we went through the main types of exceptions and learned how to raise custom errors. The last step was to see how to handle the exceptions with try-catch-else-finally blocks.

 
Extras
To view additional content login or create a free account
Categories:
Share your thoughts

No comments yet...

Signup to the newsletter
To get the latest updates from pyplane
© copyright 2019 pyplane.com