简体   繁体   中英

how to use try and except in python?

I am trying to get the user_id from the sqlite3 database in python and store in in an array. This is what I have tried:

LIST_ARRAY=[]
def start(bot, update):
    value = update.message.from_user.id
    print("VALUE first: ", value)
    try:
        for row in connection.execute("SELECT *from userdetails WHERE user_id=?", (value,)):
            print(row)
            user_id, full_name, address, phone_number, email = row
            data = [user_id]
            LIST_ARRAY[0] = data[0]
    except:
        print(LIST_OF_ADMINS)

It doesn't get the value please help me to sort this out.

My data variable doesn't get added in the list array

i cant help you with the database issue but i can answer the question of "How to use try and except in python"

Try and Except are used in python to handle errors when they occur in your code as shown below

x=[0,'It Worked',2]

try:
    print(x[4])
except IndexError:
    print("Oh No there was an error")

try:
    print(x[1])
except IndexError:
    print("Oh No there was an error")

so in the example i made above i created an array with 2 ints and a string... I then "TRY" to print the contents in x[4] which do not exist which results in a IndexError... because i told the program to print(x[4]) and the error that i prepared for occurred the "EXCEPT" statement is executed and the code beneath it is also executed

the output of the code is:

'Oh No there was an error'
'It Worked'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM