Error handling, Types of Error in py, customise Error

What’s Exception? - 3 different kinds

Pros and Cons

  1. Readability of codes

    1. LBYL most codes are doing error handling. This decreases the readablility of codes.
    2. EAFP is clear with readability.
  2. Faster under implementation

    pros and cons_faster under implementation.jpg

  3. EAFP can reduce rare conditions (OS).

  4. EAFP can avoid errors during condition checking and the actual execution of codes.

LYBL issue below

LBYL issue.jpg

getting an exception

EAFP advantage

EFPA advantage.jpg

In some cases:

We would prefer LBYL.

disadvan fo EAFP.jpg

EAFP has to start at the beginning, which increases the time consumption when exception has happened.

LBYL checking.jpg

LBYL using if function checking step by step can minimise the time consumption. No need to re-start the program from the beginning.

LBYL advan.jpg

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.

Python Exception

  1. Bulit-in exception
  2. Exception hierarchy - Parent BaseException (python library), tons of exception.
  3. Using try block for Exception Handling

chapter 8 113.jpg

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.

Exception rules.jpg

Finds what Errors

result = int(input("Enter a number here: "))

value error.jpg

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()

exception description.jpg

Common Errors and Exceptions

Common errors and exceptions.jpg

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

recursionError.jpg

def hello():
	print("hello")
	hello()

hello()

#RecursionError: maximum recursion depth exceeded while calling a Python object

LookUpError (Parent)

  1. (subclass) KeyError - dict
  2. (subclass) IndexError - list
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__))