Errors and Exception handling in Python

Ankit Deshmukh
TechGannet
Published in
3 min readJul 7, 2018

If you are writing a program and if there is any type of error in the code, program execution stops. Can we let program to continue its execution even if error occurred ? Answer is Yes, we can and for that we use error and exception handling.

What is an Exception ?

print("Hello world!)Output:
File “/home/main.py”, line 9
print(“Hello world!)
^
IndentationError: unexpected indent

We have got a syntax error and further description also saying Indentation error. This type of error and description is known as an Exception.

Check out full list of built-in exceptions here . Let’s see how to handles these errors and exceptions.

try and except

In python, basic syntax to handle errors is to use try and except statements.The code part we put in try block and handling of exception is kept in except block. Syntax as follows:

try:
#code here
except SomeException:
#If there is SomeException,then execute this block.
else:
#If there is no exception then execute this block.

Let’s consider an example where we are writing content to a file:

#sample.py
try:
f = open('C:\\Users\\ankit\\Desktop\\file.py','w')
f.write('Test write this')
except IOError:
# This will only check for an IOError exception and then execute this print statement
print("Error: Could not find file or read data")
else:
print("Content written successfully")
f.close()
Output:
Content written successfully

Let’s change the mode from w to r and try to write into a file.

#sample.py
try:
f = open('C:\\Users\\ankit\\Desktop\\file.py','r')
f.write('Test write this')
except IOError:
# This will only check for an IOError exception and then execute this print statement
print("Error: Unable to find file or operation not permitted")
else:
print("Content written successfully")
f.close()
Output:
Error: Unable to find file or operation not permitted

Look how we printed a except statement! The code still ran and executed. So, instead of breaking a code when error occurred, we are continuing to execute the program.

What if we don’t know what exception will occur ?

#sample.py
try:
f = open('C:\\Users\\ankit\\Desktop\\file.py','r')
f.write('Test write this')
except:
# This will only check for an IOError exception and then execute this print statement
print("Error: Unable to find file or operation not permitted")
else:
print("Content written successfully")
f.close()
Output:
Error: Unable to find file or operation not permitted

Done! Now, we don’t need to remember the full list of exceptions.

finally

The block of code will always be run regardless if there was an exception in the try code block.

try:
code here
...
Due to any exception, this code may be skipped!
finally:
This code block would always be executed.

Let’s see an example:

#sample.py
try
:
f = open("testfile", "w")
f.write("Test write statement")
f.close()
finally:
print("finally code always execute")
Output:
finally code always execute

One more example:

We are asking user to enter integer value:

#sample.py
try:
val = int(input("Please enter an integer: "))
except:
print("Enter Integers only!!")
finally:
print("Finally block always execute!")
Output:
Please enter an integer: 3
Finally block always execute!

Now, let’s put a string instead of an integer.

#sample.py
try:
value = int(input("Please enter an integer: "))
except:
print("Enter Integers only!!")
finally:
print("Finally block always execute!")
print(value)
Output:
Please enter an integer: hi
Enter Integers only!!
Finally block always execute!
Traceback (most recent call last):
File "/home/main.py", line 16, in <module>
print(value)
NameError: name 'value' is not defined

Even if we got exception , finally block is executed.

Here, we were trying to print the value entered by user, but we got error like “NameError: name ‘value’ is not defined” since, we got an exception. We will handle this by putting else block.

Let’s modify above program by continuously asking user until he enters integer.

#sample.py
while True:
try:
value = int(input("Please enter an integer: "))
except:
print("Enter integers only!")
continue
else:
print("Yep that's an integer!")
print(value)
break
finally:
print("Finally block always execute!")
Output:
Please enter an integer: hello
Enter integers only!
Finally block always execute!
Please enter an integer: world
Enter integers only!
Finally block always execute!
Please enter an integer: 7
Yep that's an integer!
7
Finally block always execute!

In two attempts we entered strings and we got exception. Finally block is executed every time. In last attempt we entered integer and program execution stopped since we have used break statement. In this way, we can use the errors and exception handling in our program.

That’s it!

Happy Coding!

--

--