https://docs.python.org/3/tutorial/errors.html#handling-exceptions

https://docs.python.org/3/library/exceptions.html#ValueError

try:
int("x")
except Exception as e:
'''异常的父类,可以捕获所有的异常'''
print(e)
# e变量是Exception类型的实例,支持__str__()方法,可以直接打印。
invalid literal for int() with base 10: 'x'
try:
int("x")
except Exception as e:
'''异常的父类,可以捕获所有的异常'''
print(e.args)
# e变量有个属性是.args,它是错误信息的元组。

("invalid literal for int() with base 10: 'x'",)try: datetime(2017,2,30)except ValueError as e: print(e) day is out of range for monthtry: datetime(22017,2,30)except ValueError as e: print(e) year 22017 is out of rangetry: datetime(2017,22,30)except ValueError as e: print(e) month must be in 1..12e = Nonetry: datetime(2017,22,30)except ValueError as e: print(e) month must be in 1..12e
# e这个变量在异常过程结束后即被释放,再调用也无效
 Traceback (most recent call last): File "<input>", line 1, in <module>NameError: name 'e' is not defined

errarg = None
try:
    datetime(2017,22,30)
except ValueError as errarg:
    print(errarg)
    
month must be in 1..12
errarg
Traceback (most recent call last):
  File "<input>", line 1, in <module>
NameError: name 'errarg' is not defined
try:
    datetime(2017,22,30)
except ValueError as errarg:
    print(errarg.args)

# ValueError.args 返回元组

('month must be in 1..12',)
message = None
try:
    datetime(2017,22,30)
except ValueError as errarg:
    print(errarg.args)
    message = errarg.args
    
('month must be in 1..12',)
message
('month must be in 1..12',)
try:
    datetime(2017,22,30)
except ValueError as errarg:
    print(errarg.args)
    message = errarg
    
('month must be in 1..12',)
message
ValueError('month must be in 1..12',)
str(message)
'month must be in 1..12'

分析异常信息,并根据异常信息的提示做出相应处理:

try:
y = 2017
m = 22
d = 30
datetime(y,m,d)
except ValueError as errarg:
print(errarg.args)
message = errarg
m = re.search(u"month", str(message))
if m:
dt = datetime(y,1,d) ('month must be in 1..12',)
dt
datetime.datetime(2017, 1, 30, 0, 0)

甚至可以再except中进行递归调用:

def validatedate(y, mo, d):
dt = None
try:
dt = datetime(y, mo, d)
except ValueError as e:
print(e.args)
print(str(y)+str(mo)+str(d))
message = e
ma = re.search(u"^(year)|(month)|(day)", str(message))
ymd = ma.groups()
if ymd[0]:
dt = validatedate(datetime.now().year, mo, d)
if ymd[1]:
dt = validatedate(y, datetime.now().month, d)
if ymd[2]:
dt = validatedate(y, mo, datetime.now().day)
finally:
return dt validatedate(20199, 16, 33)
('year 20199 is out of range',)
201991633
('month must be in 1..12',)
20181633
('day is out of range for month',)
2018433
datetime.datetime(2018, 4, 20, 0, 0)

python try except 出现异常时,except 中如何返回异常的信息字符串的更多相关文章

  1. Python之uiautomation模块-获取CMD窗口中所打印的文字信息

    当我们想以自动化的方式操作软件,以提高办公或测试效率时,有许多成熟的工具,比如针对Web端应用的Selenium.针对移动端应用的Appium.那么,PC端(Windows)桌面应用,又改如何处理呢? ...

  2. 【学习笔记】python 简单创建新建一个网络客户端,并返回相关的信息

    #导入socket包 import socket #使用socket.socket创建socket连接 #AF_INET表示通信类型,与IPv4对应 #SOCK_STREAM对应TCP通信 print ...

  3. 在java中捕获异常时,使用log4j打印出错误堆栈信息

    当java捕获到异常时,把详细的堆栈信息打印出来有助于我们排查异常原因,并修复相关bug,比如下面两张图,是打印未打印堆栈信息和打印堆栈信息的对比: 那么在使用log4j输出日志时,使用org.apa ...

  4. JVM反调调用优化,导致发生大量异常时log4j2线程阻塞

    背景 在使用log4j2打日志时,当发生大量异常时,造成大量线程block问题的问题. 一个关于log4j2的高并发问题:https://blog.fliaping.com/a-high-concur ...

  5. Python之路-Python中文件和异常

    一.文件的操作 open函数 在python中,使用open函数,打开一个已经存在的文件,或者新建一个新文件. 函数语法 open(name[, mode[, buffering[,encoding] ...

  6. 教你分分钟学会用python爬虫框架Scrapy爬取心目中的女神

    本博文将带领你从入门到精通爬虫框架Scrapy,最终具备爬取任何网页的数据的能力.本文以校花网为例进行爬取,校花网:http://www.xiaohuar.com/,让你体验爬取校花的成就感. Scr ...

  7. Python中出现的异常

    简单的写几种我知道的关于Python中出现的异常含义,希望大神批评指正,我只是学软件开发的菜鸟,前面的路还很长,我会努力学习! 什么是异常? 异常既是一个事件,该事件会在程序执行过程中发生,影响了程序 ...

  8. 【转载】教你分分钟学会用python爬虫框架Scrapy爬取心目中的女神

    原文:教你分分钟学会用python爬虫框架Scrapy爬取心目中的女神 本博文将带领你从入门到精通爬虫框架Scrapy,最终具备爬取任何网页的数据的能力.本文以校花网为例进行爬取,校花网:http:/ ...

  9. Python之路,Day25-----暂无正在更新中

    Python之路,Day25-----暂无正在更新中

随机推荐

  1. Flink原理(七)——动态表(Dynamic tables)

    前言 本文是结合Flink官网,个人理解所得,若是有误欢迎留言指出,谢谢!文中图皆来自官网(链接[1]). 本文将随着下面这个问题展开,针对该问题更为生动的解释可以参见金竹老师的分享(链接[2]). ...

  2. server端和前端的区别

    1.服务稳定性 server端可能会遭受各种恶意攻击和误操作 单个客户端可以意外挂掉,但是服务端不能 node中用pm2做进程守候,一旦挂掉,自己会重启 2.考虑内存和cpu(优化,扩展) 客户端独占 ...

  3. markdown锚点

    转:https://blog.csdn.net/u012260238/article/details/87815170 markdown 语法文档:https://www.w3cschool.cn/l ...

  4. Python 利用random库来实现圆周率的运算

    蒙特卡罗方法求解圆周率 随机向一个正方形以及其内切圆(半径为1)的图形中随机抛洒大量的点,计算每个点到圆心的距离从而判断该点在圆内或圆外,用圆内的点除以总点数就是π/4的值.点数越多,值就越精确. 具 ...

  5. java EL表达式中${param.name}详细

    在浏览器地址输入,表示传入一个参数test,值为123 URL:http://localhost:8888/Test/index.jsp?test=123 <body> ${test} $ ...

  6. 重新打包rpm包

    1.安装rpmrebuild 和安装rpmbuild rpmrebuild下载链接: https://sourceforge.net/projects/rpmrebuild/files/rpmrebu ...

  7. 轮播图方法一,把每个slider-item看成一个对象进行轮播

    focus-slider 只用于存放轮播图片,方便修改图片内容 其他的按照默认创建即可. 注意这里的slider.html文件是在 text文件下面  index.html <!DOCTYPE ...

  8. sublime test 3 配置安装fortran开发环境

    1.ST3下安装包管理工具Package Control https://jingyan.baidu.com/article/3c343ff7dca2b10d3779633b.html ST主界面下c ...

  9. learning java AWT 绝对定位

    import javax.swing.*; import java.awt.*; public class NullLayoutTest { Frame f = new Frame("测试窗 ...

  10. PDB符号文件

    一.什么是PDB文件 PDB(Program DataBase),全称为“程序数据库”文件.存储程序的所有调试信息数据.在编译连接时,如果选择了/debug选项或/debug:full选项,则最新的M ...