python异常处理及Url编码

#Url编码
import traceback
import urllib.parse

s = 'besttest 自动化测试'
print(urllib.parse.quote(s)) # url编码
print(urllib.parse.quote_plus(s)) # url编码,
src = 'https://www.baidu.com/s?wd=besttest%20%E8%87%AA%E5%8A%A8%E5%8C%96%E6%B5%8B%E8%AF%95'

print(urllib.parse.unquote(src)) # url解码
print(urllib.parse.unquote_plus(src)) # url解码

#Url异常处理
def main():
money = input('输入多少钱:')
months = input('还几个月:')
try:
res = calc(int(money), int(months))
except ZeroDivisionError as e: # try里面的代码如果出错了,走except里面的代码
traceback.print_exc() # 只是输出报错的详细信息而已
print('还款的月数不能小于1', e)
except ValueError as e:
print('输入必须是整数,%s' % e)
except Exception as e: # 捕获所有的异常
print('未知错误!%s' % e)
else: # 没有出错的情况下走else
print('每个月应该还%s' % res)
print('hahahahahahah')


import pymysql


def main2(sql):
try:
conn = pymysql.connect(host='122.932.122.11', user='root', password='123456', db='test')
except Exception as e:
print('数据库连接不了,%s' % e)
else:
cur = conn.cursor()
try:
cur.execute(sql)
except Exception as e:
print('sql语句有错误!%s。sql是"%s' % (e, sql))
else:
res = cur.fetchall()
return res
finally: # 不管有没有捕捉到异常,都会走这里。
cur.close()
conn.close()
posted @ 2018-03-02 14:13  Crish  阅读(158)  评论(0编辑  收藏  举报