Error handling, Types of Error in py, customise Error
Grammer Mistake - missing :
Logic Mistake (a.k.a. bugs) - ex: if and else are upside down
Exception
Solution:
LBYL (Look Before You Leap)
EAFP (Easier to Ask Forgiveness than Permission)
#LBYL approach
def safe_divide_1(x, y):
if y == 0:
print("Divide by 0 attempt detected.")
return None
else:
return x / y
# EAFP (Easier to ask forgiveness than permission)
def safe_divide_2(x, y):
try:
return x / y
except ZeroDivisionError:
print("Divide by 0 attempt detected.")
return None
# This is not real codes
# LBYL approach
def save_a_file():
result = save_prefs()
if result == 'error':
print("Preference not saved.")
return
result = save_text()
if result == 'error':
print("Not enough memory.")
return
result = save_format()
if result == 'error':
print("Format not saved.")
return
# EAFP
def save_a_file():
try:
save_prefs()
save_text()
save_format()
except:
print("Something went wrong...")
Pros and Cons
Readability of codes
Faster under implementation
EAFP can reduce rare conditions (OS).
EAFP can avoid errors during condition checking and the actual execution of codes.
LYBL issue below
getting an exception
EAFP advantage
In some cases:
We would prefer LBYL.
EAFP has to start at the beginning, which increases the time consumption when exception has happened.
LBYL using if function checking step by step can minimise the time consumption. No need to re-start the program from the beginning.
If the program aims to delete target files, EAFP is not able to recall the file has been deleted when exception happen. The exception will stop the progarm and not able to run agian.
Hence, choosing LBYL is better to check each steps before you start the program to delete files.
try:
result = 10 + "10"
except:
print("Error... something went wrong")
finally:
print(result)
#Error... something went wrong
#print(result)
#NameError: name 'result' is not defined
try:
f = open("textfile.txt", "w")
f.write("Write a test line.")
except TypeError:
print("There is a type error")
except OSError:
print("There is an OS Error")
finally:
print("This will run no matter what.")
#This will run no matter what
#testfile.text has created
try:
f = open("textfile.txt") #default read mode
f.write("Write a test line.")
except TypeError:
print("There is a type error")
except OSError:
print("There is an OS Error")
except:
print("Whatever other errors will go here")
# if there is other errors aren't the error type above
# will be print here.
finally:
print("This will run no matter what.")
#There is an OS Error cause read mode is not able to run f.write
#This will run no matter what.
#the format you use to ask users provide a correct value
def ask_for_int():
while True:
try:
result = int(input("Enter a number here: "))
except:
print("Ivalid number. Please try again.")
else:
print("Good job!")
return result
ask_for_int()
Exception rules
else and finally are optional.
Finds what Errors
result = int(input("Enter a number here: "))
Show users built-in exception description by variable method
def ask_for_int():
while True:
try:
result = int(input("Enter a number here: "))
# show users built-in exception description by variable method
except ValueError as ve:
print(ve)
print("Please try again.")
else:
print("Good job!")
return result
ask_for_int()
Type error
for i in ["a", "b", "c"]:
print(i**2)
#TypeError: unsupported operand type(s) for **
#or pow(): 'str' and 'int'
try:
for i in ["a", "b", "c"]:
print(i**2)
except TypeError:
print("We have type error!")
#We have type error!
ZeroDivisionError
print(5/0)
#ZeroDivisionError: division by zero
NameError
print(x)
#NameError: name 'x' is not defined
RecursionError
def hello():
print("hello")
hello()
hello()
#RecursionError: maximum recursion depth exceeded while calling a Python object
LookUpError (Parent)
try:
a = {1: 'hello', 2: 'how', 3: 'are', 4: 'you'}
print(a[5])
except KeyError:
print("We've got an error")
#We've got an error
lst = [1, 2, 3]
print(lst[10])
#IndexError: list index out of range
ValueError
int("hello")
#ValueError: invalid literal for int() with base 10: 'hello'
FileNotFoundError
with open("hello.txt") as f:
print(f.read())
#FileNotFoundError: [Errno 2] No such file
#or directory: 'hello.txt'
try:
with open("hello.txt") as f:
print(f.read())
except FileNotFoundError:
print("File not found...")
#File not found...
These 8 errors belong to __bulitins__module
print(dir(__builtins__))