The Python parser executes the program, detects an error, triggers an exception, the exception is triggered and is not processed, the program terminates at the current exception, and the subsequent code does not run, so you must provide an exception handling mechanism to enhance the robustness and fault tolerance of your program .
For example, we define a function
First = input (' enter divisor:'= input (' Please enter dividend:' ) int int = first/= [1, 2, 3, 4 ]print (li[5])
If the divisor second=0, then the code will throw an exception,zerodivisionerror:division by Zero, the divisor is not 0.
If the divisor input is a string, then the code will throw an exception,typeerror:unsupported operand type (s) for/: ' int ' and ' str '
At this point you need to catch the exception, when the divisor of 0 o'clock prompts the user to pass the wrong parameter. Exception handling is using the try ..... except. Key word.
First = input ('Please enter a divisor:') Second= Input ('Please enter dividend:')Try: First=int(first) second=int(second) Res= first/Secondexcept ValueError ase: #这个e代表错误信息, if the above two lines of code appear valueerror this error print (e) print ('Please enter an integer') except Zerodivisionerror asE:print (e) print ('the divisor cannot be 0')
When there is a lot of exceptions, we can write them uniformly as except Exception as E:
first = input ( " Please enter the divisor: " ) Second = input ( " " ) try : First = int (first) Second = int (second) res = First/secondexcept Exception as e: #上面代码出异常的时候走这里, print (e) print ( something went wrong .... ")
else: #没有出错, it's not a must-write.
Print (' no error ') #这个是没有异常的时候走
Print (RES)
finally:#不管出错或者没有出错都会执行它, it is not necessary to write.
Print (' I am finally ')
Now let's refine the function of the operational database
1. The database throws an exception when the connection is unsuccessful
2. When executing SQL, the SQL statement will throw an exception if it is not written correctly
def my_db2 (SQL):Try: Coon= Pymysql.connect (* *mysql_info) except Exception asRes:print ('The database connection failed') return 'The database connection failed'cur=Coon.cursor () # Creating CursorsTry: Cur.execute (SQL) #执行sql except Exception asRes:print ('SQL error, SQL is%s'%sql)return 'SQL Error' Else: ifSql.strip () [:6].upper () = ='SELECT': Res=Cur.fetchall ()Else: Coon.commit () Res='OK' finally: Cur.close () coon.close ()returnRes
Python Learning Notes (15) Exception handling