Error Exception
Published:
This lesson covers An Informal Introduction to Python 3.10.5, https://docs.python.org/3/tutorial/introduction.html
Introduction
- There are (at least) two distinguishable kinds of errors: syntax errors and exceptions.
Syntax Errors
- also known as parsing errors
- The parser repeats the problematic line and shows an arrow at the earliest error spot. File name and line number are provided to help locate
Exceptions
- Errors detected during execution
- ZeroDivisionError, NameError and TypeError
Handling Exceptions
# Repeats until a number is entered
# break if number is entered
while True:
try:
x = int(input("Please enter a number: "))
break
except ValueError:
print("Oops! no valid number. Try again...")
# Repeats until a number is entered
# break if number is entered
try:
x = 1 / 0
y = 3 + something
except(ZeroDivisionError, NameError):
pass
Raising Exceptions
try:
x = 1 / 0
except:
raise ZeroDivisionError("Hi, error in your input")
Exception Chaining
User-defined Exceptions
- Exceptions should typically be derived from the Exception class, either directly or indirectly.
Defining Clean-up Actions
- define clean-up actions that must be executed under all circumstances
try:
raise KeyboardInterrupt
finally:
print('Goodbye, world!')
def bool_return():
try:
return True
finally:
return False
print(bool_return()) # False
def divide(x, y):
try:
result = x / y
except ZeroDivisionError:
print("division by zero!")
else:
print("result is", result)
finally:
print("executing finally clause")
divide(10, 2)
divide(10, 0)
Predefined Clean-up Actions
# automatically close the file
with open("myfile.txt") as f:
for line in f:
print(line, end="")