Python Fundamentals

Exceptions


It may happen that our program is trying to a read a file which does not exist - conditions like these need to be handled by raising an exception, and in doing so interrupts the normal flow of the program. We can catch exceptions to handle them, and we will see what happens to unhandled exceptions.

Let's consider the below example - our function accepts a list of words and returns the numerical equivalent:

DIGIT_MAP = {'zero':'1','one':'1','two':'2','three':'3','four':'4','five':'5'}

def convert(s):
	number = ''
	for token in s:
		number += DIGIT_MAP[token]
	return int(number)

If we import the code in REPL and give the input "one two three four".split(), our output will be 1234

If we give an input which does not exist in the DIGIT_MAP, we will get a KeyError. If we give a different type, say, 5678 as input we will get a TypeError.

try-catch Block


Under the try block, we include the code that may generate an exception. Our except block, accepts a tuple of Exceptions types:

DIGIT_MAP = {'zero':'1','one':'1','two':'2','three':'3','four':'4','five':'5'}
x = -1
def convert(s):
	try:
		number = ''
		for token in s:
			number += DIGIT_MAP[token]
		x = int(number)
		print(f'Conversion Successful')
	except(TypeError, KeyError):	
		print(f'Conversion Failed')
	return x	

If we need more information about the error, we can do so by importing the sys module and printing sys.exc_info() and also use sys.exc_info()[1] to get the exact error.

Programmer Errors and Exception Objects


Exceptions like IndentionError, SyntaxError, NameError are the result of programmer errors. These should almost never be caught.