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. APC (Asynchronous Procedure Call)

    系统创建新线程时,会同时创建与这个线程相关联的队列,即异步过程调用(APC)的队列. 一些异步操作可以通过加入APC来实现,比如我现在学习的IO请求/完成. BOOL ReadFileEx( HAND ...

  2. request-html 简单爬虫

    import asyncio from requests_html import HTMLSession url = 'http://www.xiaohuar.com/hua/' session = ...

  3. HTML&CSS基础-边框简写属性

    HTML&CSS基础-边框简写属性 作者:尹正杰 版权声明:原创作品,谢绝转载!否则将追究法律责任. 一.HTML源代码 <!DOCTYPE html> <html> ...

  4. pyserial 挺强大的

    Ref: https://pythonhosted.org/pyserial/ pyserial写的很规范,无论安装和使用都非常的容易,目前使用下来非常好. 没有使用它做过压力测试,不知道表现如何. ...

  5. littlefs了解一下

    littlefs是一个文件系统,断电数据不会出异常,适合IOT场景.

  6. Eclipse的tab键为4个空格完整方法 附:阿里代码开发规范书

    开发规范书:http://pan.baidu.com/s/1dESdyox 1.点击 window->preference-,依次选择 General->Editors->Text ...

  7. iota妙用

    itoa可以套公式,下面的依旧会按照公式运算 package main import "fmt" func main() { const ( b = 1 << (10 ...

  8. Greenplum Segment 的检测机制

    Greenplum集群具有较好的容错性和高可用性,其中一点就体现在segment镜像机制上.接下来本文会简单地阐述segment的作用以及segment镜像机制是如何保证GP高可用的. Segment ...

  9. Kubernetes 学习11 kubernetes ingress及ingress controller

    一.上集回顾 1.Service 3种模型:userspace,iptables,ipvs 2.Service类型 ClusterIP,NodePort NodePort:client -> N ...

  10. C语言利用fgetc复制拷贝文件内容

    #include <stdio.h> #include <stdlib.h> //文件的内容复制 int main(int a,char *argv[]){ if(a!=3){ ...