Python Foundation seven-exception handling

Source: Internet
Author: User
Tags sql error

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

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.