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
NameErroroccurs when you reference a variable, function, or class that hasn’t been created yet. For example, writing
print(x)before defining x will raise this error.
ValueErroroccurs when you try to use an incompatible value. For example, trying to do
int(‘Hi’)would give you this error.
TypeErroroccurs when you try to do an operation with the wrong object type. For example, adding an integer with a string would raise this error.
AssertionErroroccurs when you assert a statement and that statement is false. We'll get into how you can assert statements in the lesson.
SyntaxErroroccurs when you’ve messed up your syntax. This is a pretty easy one to fix.
IndexErroroccurs when you try to access a value that is out of range (in a list or string)
In order to implement these, you can use:
except (exceptions that you want to ignore): #code
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.
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.