python 3.6 抓异常的方法try/except

老版本的Python,except语句写作"except Exception, e",Python 2.6后应写作"except Exception as e"。
try:
  ...
except Exception as e:
  ...
  1. str(e)
    返回字符串类型,只给出异常信息,不包括异常信息的类型,如1/0的异常信息
    ‘integer division or modulo by zero’

  2. repr(e)
    给出较全的异常信息,包括异常信息的类型,如1/0的异常信息
    “ZeroDivisionError(‘integer division or modulo by zero’,)”

  3. e.message
    获得的信息同str(e)

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

与Python异常相关的关键字:
关键字          关键字说明
raise           抛出/引发异常
try/except      捕获异常并处理
pass            忽略异常
as              定义异常实例(except IOError as e)
finally         无论是否出现异常,都执行的代码
else            如果try中的语句没有引发异常,则执行else中的语句
except
老版本的Python,except语句写作"except Exception, e",Python 2.6后应写作"except Exception as e"。

https://blog.csdn.net/u010532552/article/details/53995075

 https://www.cnblogs.com/Simon-xm/p/4073028.html

猜你喜欢

转载自blog.csdn.net/qq_27361945/article/details/83415071