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. 12.安装olny office服务---不成功

    安装olny office服务 在01.centos7环境准备的基础上安装olny office服务 参考博客:https://blog.csdn.net/networken/article/deta ...

  2. C++(四十)— C++中一个class类对象占用多少内字节

    一个空的class在内存中多少字节?如果加入一个成员函数后是多大?这个成员函数存储在内存中什么部分? 一个Class对象需要占用多大的内存空间.最权威的结论是: 非静态成员变量总合. 加上编译器为了C ...

  3. mysql存储、function、触发器等实例

    一.创建数据库&表 DROP DATABASE IF EXISTS security; CREATE database security; USE security; CREATE TABLE ...

  4. 局部敏感哈希算法(Locality Sensitive Hashing)

    from:https://www.cnblogs.com/maybe2030/p/4953039.html 阅读目录 1. 基本思想 2. 局部敏感哈希LSH 3. 文档相似度计算 局部敏感哈希(Lo ...

  5. Tensorflow细节-P199-数据集

    数据集的基本使用方法 import tempfile import tensorflow as tf input_data = [1, 2, 3, 5, 8] # 这不是列表吗,为什么书里叫数组 da ...

  6. 马尔科夫链蒙特卡洛(MCMC) -- 学习笔记

    https://blog.csdn.net/m0_38088359/article/details/83480258 https://blog.csdn.net/shenxiaolu1984/arti ...

  7. Java【基础学习】向下转型和上转型例子

    Java小白应付期末考试QWQ class Animal{ public void move() { System.); } } class Dog extends Animal{ public vo ...

  8. 【JQuery】操作前端控件知识笔记

    一.jQuery操作复选框checkbox 1.设置选中.取消选中.获取被选中的值.判断是否选中等 注意:操作checked.disabled.selected属性,强制建议只用prop()方法!!, ...

  9. leetcode解题报告(28):Remove Linked List Elements

    描述 Remove all elements from a linked list of integers that have value val. Example Given: 1 --> 2 ...

  10. poj 3735 稀疏矩阵矩阵快速幂

    设人数为 $n$,构造 $(n + 1) \times (n + 1)$ 的矩阵 得花生:将改行的最后一列元素 $+ 1$ \begin{gather}\begin{bmatrix}1 & 0 ...