Handling Errors in Python

Handling errors is an important aspect of any programming language because, in case of issues, the program/script should not crash but should be able to behave differently according to the specific issue when possible. This is done in Python by writing the main code within a try block and the exception needs to be written within an except block. In this way, in case of issues, the program does not stop but simply continues with the alternative block of code provided.

#Example without error
#The code will print "Hello!"
try:
	print("Hello!") 
except:
	print("Error!")
	
#Example with error
#Variable a does not exist
#The code will print "Error!"
try:
	print(a) #This cannot be printed
except:
	print("Error!")

It is also possible to react differently based on the type of error by using several except blocks associated to the name of the specific error.

try:
	print(a)    # Here the variable is not defined
except NameError:
	print("Name of variable not defined!") # This is executed
except:
	print("Other Error!")
	
l1=[3,5]
try:
	print(l1[2])  # This is outside the list
except IndexError:
	print("Out of List Range!") # This is executed
except:
	print("Other Error!")
	
try:
	print(5/0)   # This is a division by 0
except NameError:
	print("Name of variable not defined!")
except IndexError:
	print("Out of List Range!")
except:
	print("Other Error!") # This is executed because it is not NameError or IndexError

Python also allows to run a specific block in case of no errors. This is done by using the else keyword.

try:
	print("Hello")    # This is executed
except:
	print("Error!")
else:
	print("No errors triggered!")  # This is also executed
	
try:
	print(a)         # a does not exist
except:
	print("Error!")   # This is executed
else:
	print("No errors triggered!")  # This is NOT executed

There is also the possibility to run a block which is independent by any error triggered, the block within the finally keyword will run if there is an error or not.

try:
	print("Hello")    # This is executed
except:
	print("Error!")
finally:
	print("Code executed here in any case!")  # This is also executed
	
try:
	print(a)         # a does not exist
except:
	print("Error!")   # This is executed
finally:
	print("Code executed here in any case!")  # This is also executed

In case the program needs to throw a specific error in a certain occasion it is possible to use the keyword raise and then mention in writing what is the issue encountered.

a=2
if(a%2!=0):  # If a is an odd number
	raise Exception("The variable can only have even numbers!")
else:
	print(a) # This will be executed because a is even

b=3
if(b%2!=0):  # If b is an odd number
	raise Exception("The variable can only have even numbers!")  # The exception is triggered
else:
	print(b)

This concludes this overview on handling errors in Python. Use the console below and create some code to handle errors.