python try except返回异常的信息字符串代码实例

问题

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',)
('month must be in 1..12',)
('day is out of range for month',)
datetime.datetime(2018, 4, 20, 0, 0)

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持我们。

赞 (0)

相关推荐

  • 对python中的try、except、finally 执行顺序详解

    如下所示: def test1(): try: print('to do stuff') raise Exception('hehe') print('to return in try') return 'try' except Exception: print('process except') print('to return in except') return 'except' finally: print('to return in finally') return 'finally'

  • python try except 捕获所有异常的实例

    如下所示: try: a=1 except Exception as e: print (e) import traceback import sys try: a = 1 except: traceback.print_exc() #sys.exc_info() 以上这篇python try except 捕获所有异常的实例就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持我们.

  • python try 异常处理(史上最全)

    在程序出现bug时一般不会将错误信息显示给用户,而是现实一个提示的页面,通俗来说就是不让用户看见大黄页!!! 有时候我们写程序的时候,会出现一些错误或异常,导致程序终止. 为了处理异常,我们使用try...except 把可能发生错误的语句放在try模块里,用except来处理异常. except可以处理一个专门的异常,也可以处理一组圆括号中的异常, 如果except后没有指定异常,则默认处理所有的异常. 每一个try,都必须至少有一个except 在python的异常中,有一个万能异常:Exc

  • Python中的异常处理try/except/finally/raise用法分析

    本文实例分析了Python中的异常处理try/except/finally/raise用法.分享给大家供大家参考,具体如下: 异常发生在程序执行的过程中,如果python无法正常处理程序就会发生异常,导致整个程序终止执行,python中使用try/except语句可以捕获异常. try/except 异常的种类有很多,在不确定可能发生的异常类型时可以使用Exception捕获所有异常: try: pass except Exception, e: print Exception, ":"

  • Python 错误和异常代码详解

    程序中的错误一般被称为 Bug,无可否认,这几乎总是程序员的错... 程序员的一生,始终伴随着一件事 - 调试(错误检测.异常处理).反反复复,最可怕的是:不仅自己的要改,别人的也要改...一万头草泥马奔腾而过! 错误 程序错误,主要分为三类: 语法错误 逻辑错误 运行时错误 语法错误 语法错误(也称:解析错误):是指不遵循语言的语法结构引起的错误(程序无法正常编译/运行). 在编译语言(例如:C++)中,语法错误只在编译期出现,编译器要求所有的语法都正确,才能正常编译.不过对于直译语言(例如:

  • Python使用try except处理程序异常的三种常用方法分析

    本文实例讲述了Python使用try except处理程序异常的三种常用方法.分享给大家供大家参考,具体如下: 如果你在写python程序时遇到异常后想进行如下处理的话,一般用try来处理异常,假设有下面的一段程序: try: 语句1 语句2 . . 语句N except .........: do something ....... 但是你并不知道"语句1至语句N"在执行会出什么样的异常,但你还要做异常处理,且想把出现的异常打印出来,并不停止程序的运行,所以在"except

  • Python中的错误和异常处理简单操作示例【try-except用法】

    本文实例讲述了Python中的错误和异常处理操作.分享给大家供大家参考,具体如下: #coding=utf8 print ''''' 程序编译时会检测语法错误. 当检测到一个错误,解释器会引发一个异常,并显示异常的详细信息. 在代码中添加错误检测及异常处理,只需要将代码封装在try-except语句中. try: try_suite except : except_suite ------------------------------------------------------------

  • python try except返回异常的信息字符串代码实例

    问题 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__()方法,可以直接打印. inv

  • Python中join()函数多种操作代码实例

    这篇文章主要介绍了Python中join()函数多种操作代码实例,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下 Python中有.join()和os.path.join()两个函数,具体作用如下: . join(): 连接字符串数组.将字符串.元组.列表中的元素以指定的字符(分隔符)连接生成一个新的字符串 os.path.join(): 将多个路径组合后返回 对序列进行操作(分别使用' ' .' - '与':'作为分隔符) a=['1aa','

  • Python实现简单网页图片抓取完整代码实例

    利用python抓取网络图片的步骤是: 1.根据给定的网址获取网页源代码 2.利用正则表达式把源代码中的图片地址过滤出来 3.根据过滤出来的图片地址下载网络图片 以下是比较简单的一个抓取某一个百度贴吧网页的图片的实现: # -*- coding: utf-8 -*- # feimengjuan import re import urllib import urllib2 #抓取网页图片 #根据给定的网址来获取网页详细信息,得到的html就是网页的源代码 def getHtml(url): pag

  • JavaScript 截取字符串代码实例

    这篇文章主要介绍了JavaScript 截取字符串代码实例,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下 代码如下 <script> $(document).ready(function () { //下标从0开始 let str = '123456789'; //使用一个参数 console.log(str.slice(3)) //从第4个字符开始,截取到最后个字符;返回"456789" console.log(str.

  • python基于FTP实现文件传输相关功能代码实例

    这篇文章主要介绍了python基于FTP实现文件传输相关功能代码实例,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下 本实例有文件传输相关功能,包括:文件校验.进度条打印.断点续传 客户端示例: import socket import json import os import hashlib CODE = { '1001':'重新上传文件' } def file_md5(file_path): obj = open(file_path,'rb

  • Python编程实现线性回归和批量梯度下降法代码实例

    通过学习斯坦福公开课的线性规划和梯度下降,参考他人代码自己做了测试,写了个类以后有时间再去扩展,代码注释以后再加,作业好多: import numpy as np import matplotlib.pyplot as plt import random class dataMinning: datasets = [] labelsets = [] addressD = '' #Data folder addressL = '' #Label folder npDatasets = np.zer

  • python图片二值化提高识别率代码实例

    这篇文章主要介绍了python图片二值化提高识别率代码实例,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下 代码如下 import cv2from PIL import Imagefrom pytesseract import pytesseractfrom PIL import ImageEnhanceimport reimport string def createFile(filePath,newFilePath): img = Image

  • Python小程序 控制鼠标循环点击代码实例

    这篇文章主要介绍了Python小程序 控制鼠标循环点击代码实例,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下 from ctypes import * import pyautogui import time time.sleep(5) while 1: pyautogui.click(400, 400, clicks=1, interval=0.0, button='left') time.sleep(10) Note: 坐标(400,400

  • Python通过递归获取目录下指定文件代码实例

    这篇文章主要介绍了python通过递归获取目录下指定文件代码实例,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下 获取一个目录下所有指定格式的文件是实际生产中常见需求. import os #递归获取一个目录下所有的指定格式的文件 def get_jsonfile(path,file_list): dir_list=os.listdir(path) for x in dir_list: new_x=os.path.join(path,x) if

  • Python matplotlib以日期为x轴作图代码实例

    这篇文章主要介绍了Python matplotlib以日期为x轴作图代码实例,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下 效果图如下 代码如下 from datetime import datetime, date, timedelta import matplotlib.pyplot as plt import tushare as ts plt.rcParams['font.sans-serif'] = ['SimHei'] #显示中文

随机推荐