top of page

Handling Exceptions in Python

Introduction


If you've worked with Python before, you've probably encountered some error or the other, be it a ValueError, to do with using the wrong data types, or a SyntaxError, when you write an invalid statement.


Luckily, Python allows us to catch those errors using just a few lines of code.


Tower Heights


Suppose we wanted to convert the height of some towers into nanometers, for whatever reason. See if you can spot the error:

heights = {
	"Eiffel Tower" : "984",
	"Burj Khalifa" : "2717 feet",
	"Big Ben" : "315 ft"
}


def main():
	tower = input("Enter a tower: ")
	nm = ftToNm(heights[tower])
	print(f"{nm} nm away")


def ftToNm(ft):
	return ft * 304800000

main()

Everything is just about fine aside from the fact that our dictionary stores its heights as strings, rather than integers.


If I were to enter "Eiffel Tower" into the terminal, I would be met with a MemoryError...


Out of all the possible errors, a MemoryError seems a little strange, in this case.


Well, recall that we can perform arithmetic operations on strings too. So when we passed the string through ftToNm( ), an extremely large string was produced, causing issues in memory.


Instead, we can try converting the string number to an int through casting.

nm = int(ftToNm(heights[tower]))

But non-numerical strings (like "2717 feet") would raise a ValueError if converted.


In order to catch this error, we use the try and except commands, in which Python allows us to attempt to execute some code, and if a certain error pops up, a different branch of code executes.


We can modify main( ) as such:

def main():
	tower = input("Enter a tower: ")
	try:
		nm = int(ftToNm(heights[tower]))
	except ValueError:
		print(f"Can't convert {heights[tower]} to an int")
		return
	print(f"{nm} nm away")

We can even add multiple exceptions to catch multiple errors:

def main():
	tower = input("Enter a tower: ")
	try:
		nm = int(ftToNm(heights[tower]))
	except KeyError:
		print(f"Can't convert {tower} is not in dictionary")
		return
	except ValueError:
		print(f"Can't convert {heights[tower]} to an int")
		return
	print(f"{nm} nm away")

In this case, a KeyError emerges when a dictionary key does not exist--like if I were to input the "Tower of Pisa."



Final Thoughts


Aside from the few we've looked at, there are plenty more errors that can be caught in Python. Thanks for reading!

Comments


bottom of page