Python error handling Flashcards
Objectives
Read and use error output from exceptions.
Properly handle exceptions.
Raise exceptions with useful error messages.
Use exceptions to control a program’s flow.
traceback
A traceback is the body of text that can point to the origin (and ending) of an unhandled error.
Try and except blocks
try:
open(‘config.txt’)
except FileNotFoundError:
print(“Couldn’t find the config.txt file!”)
**Revert to catching FileNotFoundError, and then add another except block to catch PermissionError:
def main():
try:
configuration = open(‘config.txt’)
except FileNotFoundError:
print(“Couldn’t find the config.txt file!”)
except IsADirectoryError:
print(“Found config.txt but it is a directory, couldn’t read it”)
Exception errors
Even though you can group exceptions together, do so only when there’s no need to handle them individually. Avoid grouping many exceptions together to provide a generalized error message.
What are three elements that you might find in a traceback?
A file path, line number, and exception
What two keywords would you use for handling exceptions?
try and except
Why would using except Exception be unhelpful?
This technique usually hides what the underlying problem that caused the error is
When can it be useful to use as err in an except block
When a raised exception will be reused or inspected, the as err statement can help.
What is the right syntax to catch two exceptions in the same except line?
except (ValueError, TypeError):
errors
syntax errors -Raised when a syntax error occurs
RuntimeError–Raised when an error occurs that do not belong to any specific exceptions
example: trees = [‘Douglas Fir’, ‘Oak’, ‘Balsam fir’]
last_tree = tree[3]
print(f’The last tree is {last_tree}.’)
*** list index is out of range
logic errors:
A logical error occurs in Python when the code runs without any syntax or runtime errors but produces incorrect results due to flawed logic in the code. These types of errors are often caused by incorrect assumptions, an incomplete understanding of the problem, or the incorrect use of algorithms or formulas.
In order to display an error msge when an error occurs
The code to run should be in try block, and the code to run if there is an error should be in an except block
a = float(input(“Enter a number.”))
b = float(input(“Enter a numberto divide by.”))
try:
print(f”The answer is {a/b}.”)
except:
print(“This did not work.Did you try to divide by zero or enter an invalid number?”)
else:
print(“You successfully divided two numbers.”)
finally:
print(“Thank you for playing.”)
** The finally statement will run regardless of which pieces of code above it run
** The try and except parts do not both run as part of a try/except/finally block. Either try part runs or except part runs