Intro to Python Errors and Exceptions: Behind the Scenes
📌 Intro to Python Errors and Exceptions: Behind the Scenes ⚠️
Hi! Welcome to Week 4 and to this short introduction to Python errors and exceptions.
This topic is essential for the process of debugging. When there are errors or bugs in a program (syntax or logical errors), you can usually detect them and correct them by reading the error message displayed. It’s like working as a detective 🔎. You need to read the error message, interpret it, and try to guess what might be causing the problem. It’s actually pretty fun if you think about it. You can fix the program by solving the “puzzle” and we usually learn very much from long debugging sessions. You need to do research, experiment, test, and fix, so they are amazing opportunities to learn.
It all begins with a simple error message, and this is what we will discuss in this short introduction, a few of the different types of error messages that you can get in a Python program. Let’s begin!
Vocabulary
- Exception: an exception is an unexpected error or event that occurs while the program is running and changes the flow of execution.
- Bug: logical error in a program.
- Debugging: the process of finding and fixing bugs in your code.
🚩 IndexError
Perhaps you familiarized yourself with this error message during week 3, where you learned how to work with lists and tuples. This exception occurs when you try to access an index beyond the boundaries of a list, tuple, or string.
According to the Python Documentation:
"Raised when a sequence subscript is out of range. (Slice indices are silently truncated to fall in the allowed range; if an index is not an integer, TypeError is raised.)" https://docs.python.org/3/library/exceptions.html#IndexError
This is an example with a tuple:
🚩 TypeError
A TypeError is an exception that is raised when an operation is applied to a value of an inappropriate type.
For example, you may see this exception if you pass an argument of the wrong data type to a Python built-in function, like in the image below where we pass a list as the argument to int(). This function converts the argument to an integer, but a list is not a valid input for this function, so you see an exception thrown.
💡 Note: You will see a descriptive message telling you more information about the error and the appropriate data types for the function.
According to the Python documentation:
“Raised when an operation or function is applied to an object of inappropriate type. The associated value is a string giving details about the type mismatch.” https://docs.python.org/3/library/exceptions.html#TypeError
This is another example, passing a value that has no length to the function len():
Here you can see an example of this exception when we try to concatenate an integer with a tuple. The data type of the operand is not appropriate for the operation.
Interestingly, you can also get this exception if you try to use a value that is not an integer as an index:
🚩 ValueError
A ValueError exception is raised when you use an inappropriate value of a valid type. The type is compatible with the operation of parameter, but the value is not permitted.
According to the Python documentation:
“Raised when an operation or function receives an argument that has the right type but an inappropriate value, and the situation is not described by a more precise exception such as IndexError.” https://docs.python.org/3/library/exceptions.html#ValueError
For example, in the image below we see this exception because we pass the string “Donut” to the built-in function int(). You may ask, why don’t we get a TypeError? This is because the int() function can take strings, but those string have to represent numbers to be successfully converted (casted) to integers (e.g. “56”). In this case, the string (value) is not valid.
This exception is also raised when we try to unpack a tuple through tuple assignment.
Here, we are trying to create more variables than the number of values contained in the tuple.
🚩 NameError
This exception, NameError, is raised when a local or global variable is used or accessed without being defined first, when you are trying to access it before it even exists in the scope.
According to the Python documentation:
“Raised when a local or global name is not found. This applies only to unqualified names. The associated value is an error message that includes the name that could not be found.” https://docs.python.org/3/library/exceptions.html#NameError
🚩 SyntaxError
A SyntaxError occurs when a line of code has an invalid syntax, when the rules to write code in the Python programming language are broken.
For example, a binary operator such as the multiplication operator (*) has to have two operands, one located to its left and one located to its right. In the example below, the order is not correct, so a syntax error is raised.
According to the Python documentation:
“Raised when the parser encounters a syntax error. This may occur in an import statement, in a call to the built-in functions exec() or eval(), or when reading the initial script or standard input (also interactively).” https://docs.python.org/3/library/exceptions.html#SyntaxError
I really hope that you liked this tutorial and found it helpful 😀. Please do not hesitate to ask on the discussion forums or right below this post if you have any questions. Community TAs and your classmates will be there to help you. 👍
Estefania.
Your blog posts are some of the best I have found for introductory Python; you explain everything in a way that is super easy to follow and intuitive - keep up the good work!
ReplyDeleteThanks, Estefania! I find hearing a subject explained in different ways, extremely helpful. I appreciate your hard work very much!
ReplyDelete