Catch The Error

When we meet an error or an exception while our code is running, Python will normally stop and generate an error message in red.
We can handle it using try, if statement, except & raise our own error methodology.

Example #1

lucky_nums = [9,66,12,89,21,46,90]
print(lucky_nums[10])

We will get an error message, that mifght be not clear for us or final user:

lucky_nums = [9,66,12,89,21,46,90]
print(lucky_nums)
min = 0
try:
    lucky_nums[10]
except IndexError:
    print('list index out of range')
much better 🙂
lucky_nums = [9,66,12,89,21,46,90]
print(lucky_nums)
min = 0
try:
    lucky_nums(10)
except IndexError:
    print('list index out of range')
except Exception as Ex:
    print('Warning',Ex,type(Ex))
else:
    print("good shot! this is your lucky number!")

Example #2

Let’s create a simple functions at first.

def Login(FirstName, LastName, BDate):
    return '{}{}{}'.format(FirstName[0:3],LastName[0:4],BDate[2:])

FirstName = input("First Name: ")
LastName = input("Last Name: ")
BDate = input ("Year of Birth: ")

print("Login: ", Login(FirstName,LastName,BDate))

Inside we need to declare possible error that we might get while someone put wrong Name, Surname or Year:

class WrongInputs(Exception):
    pass
def Login(FirstName, LastName, BDate):
    try:
        Login_FirstName = FirstName[0]
    except:
        raise WrongInputs("Incorrect Name")
    if len(LastName) <1:
        raise WrongInputs("Incorrect Surname")
    Login_FirstName = LastName[0]
    if not BDate.isnumeric():
        raise WrongInputs("Incorrect Value for Year of Birth")
    Login_Bdate = BDate[0]

    return '{}{}{}'.format(FirstName[0:3], LastName[0:4], BDate[2:])

FirstName = input("First Name: ")
LastName = input("Last Name: ")
BDate = input ("Year of Birth: ")
try:
    print("Login: ", Login(FirstName, LastName, BDate))
except WrongInputs as Ex:
    print("Error while Login creating: ",Ex)
except IndexError:
    print('list index out of range')

Read data with OS

OS implements some useful functions on pathnames. Path parameters can be passed as either strings, or bytes. Applications are encouraged to represent file names as (Unicode) character strings.

import os

#The function returns a tuple of data retrieved from the csv file
def get_data(csv_file):

 data = []  # declare an empty list for data from a file

  if os.path.isfile(csv_file):  # file source verification
      with open(csv_file, "r") as content:  # open 4 read
          for lines in content:
             lines = lines.replace("\n", "")
             lines = lines.replace("\r", "")  # remove line breaks
              
# adding items to the stamp and the stamp to the list
              data.append(tuple(lines.split(",")))
    else:
        print ("Chosen file", csv_file, "does not exist!")

    return tuple(data)  # transform the list into a tuple and return it
samp = r"samp.csv"
whole_file = get_data(samp)

print(whole_file)
print(whole_file[2:3])
readsamp = whole_file[2:3]
print(readsamp)
print(type(readsamp))

readsamp2 = str(readsamp)
print(readsamp2)
print(type(readsamp2))
#saving data to a new csv file
plik = open("samp2.csv", "w")
plik.write(readsamp2)
plik.close


# change the content
sourcefile = open(samp).readlines()
destinyline = open(samp, "w")

for x in sourcefile:
    destinyline.write(x.replace("X", "Y"))

destinyline.close()