3️⃣

19.3 Exceptions

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:
  • NameError occurs 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.
  • ValueError occurs when you try to use an incompatible value. For example, trying to do int(‘Hi’) would give you this error.
  • TypeError occurs when you try to do an operation with the wrong object type. For example, adding an integer with a string would raise this error.
  • AssertionError occurs when you assert a statement and that statement is false. We'll get into how you can assert statements in the lesson.
  • SyntaxError occurs when you’ve messed up your syntax. This is a pretty easy one to fix.
  • IndexError occurs 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
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.
 
⚖️
Copyright © 2021 Code 4 Tomorrow. All rights reserved. The code in this course is licensed under the MIT License. If you would like to use content from any of our courses, you must obtain our explicit written permission and provide credit. Please contact classes@code4tomorrow.org for inquiries.