随笔 - 17  文章 - 0  评论 - 0  阅读 - 10445 

异常处理try,except,else,finally的使用和实例。

 

1、异常处理说明

try:
    5/0
except Exception as e:   #这个exception 能捕捉到所有的异常
    print('异常信息:',e)     #这个是出了异常的话,怎么处理,e代表异常信息
else:
    print('没有出异常的话,走这里')   #若是没有出现异常,运行else
finally:
    print('这里是finally')   #无论是否出现异常,都会执行finally

 

2、判断小数(判断s是否可以转换为float类型的)

复制代码
def is_float(s):
    try:
        float(s)
    except Exception as e:
        return False
    return True

res=is_float(-1.2)
print(res)
复制代码

 

3、操作数据库(mysql)

复制代码
import pymysql

def OpertionMysql(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)   #建立连接
    except Exception as e:
        return {"code":308,"msg":"数据库连接异常%s"%e}
    cur = conn.cursor(cursor=pymysql.cursors.DictCursor)    #建立游标
    try:
        cur.execute(sql)   #执行sql
    except Exception as e:
        return {"code":309,"msg":"sql错误!%s"%e}
    else:
        if sql.startswith('select'):  # 判断是什么语句
            res = cur.fetchone()
        else:
            conn.commit()
            res = 88
        return res
    finally:
        cur.close()
        conn.close()

res = OpertionMysql('192.168.160.3','root','123456','hqtest','xxxxxx')
print(res)
复制代码

 

posted on   笔-记  阅读(284)  评论(0编辑  收藏  举报
编辑推荐:
· 对象命名为何需要避免'-er'和'-or'后缀
· SQL Server如何跟踪自动统计信息更新?
· AI与.NET技术实操系列:使用Catalyst进行自然语言处理
· 分享一个我遇到过的“量子力学”级别的BUG。
· Linux系列:如何调试 malloc 的底层源码
阅读排行:
· JDK 24 发布,新特性解读!
· C# 中比较实用的关键字,基础高频面试题!
· .NET 10 Preview 2 增强了 Blazor 和.NET MAUI
· SQL Server如何跟踪自动统计信息更新?
· windows下测试TCP/UDP端口连通性
点击右上角即可分享
微信分享提示