Python异常处理总结

Python异常处理流程如下:

#!/usr/bin/python
#-*- coding:utf-8 -*-
import sys
reload(sys)
sys.setdefaultencoding('utf8')

def test1():
    try:
        print('In try.')
        raise GeneratorExit
        raise FloatingPointError
        #raise Exception('hehe')
        #return 'try'
    except GeneratorExit as e:
        print eexcept FloatingPointError:
        print('In FloatingPointError')
    except Exception:
        print('In except')
        #return 'exception'
    else:
        print('In else')
        return 'else'
    finally:
        print('In finally')
        #return 'finally'

print(test1())

1. except语句

  用于捕捉发生的错误,except X语句要放在except之前,否则except X语句将无法执行。

2. else语句

  如果try中没有发生异常,将会执行else语句

3. finally语句

  finally语句在程序返回之前执行,也就是说,它总会执行。

4. return

  如果finally中有return语句,则执行finally中的return语句返回;如果finally中没有return语句,则返回到转入finally之前的代码段中返回。

5. 打印异常信息

def Mysql_select(db_host,sql):
    try:
        cnx = pymysql.connect(host='192.168.1.15',port= 3306,user = 'root',passwd='123123',db='test',timeout=5)
    # except TypeError:
    #     print 'In typeerror'
    except Exception,e:
        print repr(e)

1、str(e)

  返回字符串类型,只给出异常信息,不包括异常信息的类型,如1/0的异常信息

  ‘__init__() got an unexpected keyword argument 'timeout'’

2、repr(e)

  给出较全的异常信息,包括异常信息的类型,如1/0的异常信息

  TypeError("__init__() got an unexpected keyword argument 'timeout'",)

3、e.message

  获得的信息同str(e)

4、采用traceback模块

  需要导入traceback模块,此时获取的信息最全,与python命令行运行程序出现错误信息一致。使用traceback.print_exc()打印异常信息到标准错误,就像没有获取一样,或者使用traceback.format_exc()将同样的输出获取为字符串。你可以向这些函数传递各种各样的参数来限制输出,或者重新打印到像文件类型的对象。

原文地址:https://www.cnblogs.com/guosq/p/6385286.html