Exceptions

Have you noticed that you get different errors when trying to do different invalid operations? Turns out, if you want to specify which error you would like to except and which you want to stop the code, these names come in handy. When specifying which exceptions you would like to except, except can work with one or more errors. If you wanted just one error, you would simply do  except (error):. If you wanted to except several errors but have them do the same thing, you could do except (error1) and (error2):. For a full list of exceptions, see the bottom of this website. For now, we’ll just cover NameError, TypeError, AssertionError, SyntaxError, and IndexError:

In order to implement these, you can use:

except (exceptions that you want to ignore):
	#code

Example:

try:
	x = 1
	y = "hi"
	x + y
except TypeError: #this will only run if there's a TypeError
	print("incorrect types, try again")
except NameError: #this will only run if there's a NameError
	print("maybe you forgot to create that")

View code on GitHub.

This allows you to except certain errors but still get the error messages from errors you didn’t expect.

Practice

Type Checker

Create a function that takes one argument and prints arg * 4. If the argument is not the correct type, print a message saying so. It should be able to run through the list provided.

💻 Template code

Solution code

Previous Section

19.2 Try/Except

Next Section

19.4 Else & Assert