异常处理常用的是这种结构,一般去掉finally
可以在else里嵌套
比如说之前连接mysql查询就用到了异常处理
#!/usr/bin/python # -*- coding: UTF-8 -*- import pymysql # 打开数据库连接 db = pymysql.connect(host='localhost', user='root', passwd='199126', db='test', port=3306, charset='utf8') cursor = db.cursor() # SQL 查询语句 sql = "SELECT * FROM course" try: # 执行SQL语句 cursor.execute(sql) # 获取所有记录列表 results = cursor.fetchall() for row in results: id = row[0] name = row[1] # 打印结果 print("id=%s,name=%s" % (id, name)) except: print("Error: unable to fecth data") else: print("no 异常") # 关闭数据库连接 db.close()