Use and examples of exception handling try,except,else,finally.
1. Exception Handling Instructions
Try: 5/0exceptException as E:#This exception can catch all the anomalies. Print('Exception Information:'E#This is an unusual word, how to deal with it, E for the exception informationElse: Print('without exception, go here .')#If no exception occurs, run elsefinally: Print('this is finally .')#the finally is executed regardless of whether an exception occurs
2, Judge the decimal (determine if s can be converted to float type)
def Is_float (s): Try : float (s) except Exception as E: return False return trueres=is_float ( -1.2)print(res)
3. Operation Database (MySQL)
ImportPymysqldefOpertionmysql (host,user,passwd,db,sql,port=3306,charset='UTF8'): Try: Conn= Pymysql.connect (Host=host,user=user,passwd=passwd,port=port,db=db,charset=charset)#Establish a connection exceptException as E:return{"Code": 308,"msg":"database Connection Exception%s"%e} cur= Conn.cursor (Cursor=pymysql.cursors.dictcursor)#Creating Cursors Try: Cur.execute (SQL)#Execute SQL exceptException as E:return{"Code": 309,"msg":"SQL Error! %s"%e}Else: ifSql.startswith ('Select'):#judge what the statement isres =Cur.fetchone ()Else: Conn.commit () Res= 88returnResfinally: Cur.close () conn.close () Res= Opertionmysql ('192.168.160.3','Root','123456','hqtest','xxxxxx')Print(RES)
Python Foundation seven-exception handling