美文网首页
异常Exception

异常Exception

作者: wangyu2488 | 来源:发表于2019-12-22 15:30 被阅读0次

    2019年11月27日

    # coding=utf-8
    
    import datetime as dt
    
    def read_date(in_date):
        try:
            tmpDate = dt.datetime.strptime(str_date, '%Y-%m-%d')
            return tmpDate
        except Exception as e:
            print('处理异常')
            print(e)
    
    # 非法时间 直接调用会报异常
    str_date = '2011-13-18'
    print('日期 = {0}'.format(read_date(str_date)))
    

    /usr/local/bin/python3.8 /Users/mac/Documents/wangyu/gitRepository/HelloProj/com/pkg1/Hello.py

    处理ValueError异常

    time data '2011-13-18' does not match format '%Y-%m-%d'

    日期 = None

    Process finished with exit code 0

    二.多重异常捕获
    1.用法1

    # coding=utf-8
    
    import datetime as dt
    
    def read_date_from_file(filename):
        try:
            file = open(filename)
            in_date = file.read()
            in_date = in_date.strip()
            date = dt.datetime.strptime(in_date, '%Y-%m-%d')
            return date
        except ValueError as e:
            print('处理ValueError异常')
            print(e)
        except FileNotFoundError as e:
            print('处理FileNotFoundError异常')
            print(e)
        except OSError as e:
            print('处理OSError异常')
            print(e)
    
    date = read_date_from_file('readme.txt')
    print('日期 = {0}'.format(date))
    

    1.1 添加finally 用法 推荐用下面的1.2 with as

    # coding=utf-8
    
    import datetime as dt
    
    def read_date_from_file(filename):
        try:
            file = open(filename)
        except OSError as e:
            print('打开文件失败')
        else:
            print('打开文件成功')
            try:
                in_date = file.read()
                in_date = in_date.strip()
                date = dt.datetime.strptime(in_date, '%Y-%m-%d')
                return date
            except ValueError as e:
                print('处理ValueError异常')
            except OSError as e:
                print('处理OSError异常')
            finally:
                file.close()
    
    date = read_date_from_file('readme.txt')
    print('日期 = {0}'.format(date))
    

    1.2 with as用法 解决上面代码层级混乱问题 【with as 提供一个代码块,在as后面声明的资源变量,会等with as代码块执行完后,自动释放】

    import datetime as dt
    
    def read_date_from_file(filename):
        try:
            with open(filename) as file:
                in_date = file.read()
    
            in_date = in_date.strip()
            date = dt.datetime.strptime(in_date, '%Y-%m-%d')
            return date
        except ValueError as e:
            print('处理ValueError异常')
        except OSError as e:
            print('处理OSError异常')
    
    date = read_date_from_file('readme.txt')
    print('日期 = {0}'.format(date))
    

    2.用法2 注意(OSError可以捕获所有他的子类异常)

    import datetime as dt

    def read_date_from_file(filename):
        try:
            file = open(filename)
            in_date = file.read()
            in_date = in_date.strip()
            date = dt.datetime.strptime(in_date, '%Y-%m-%d')
            return date
        except (ValueError, OSError) as e:
            print('调用方法method1处理...')
            print(e)
    
    date = read_date_from_file('readme.txt')
    print('日期 = {0}'.format(date))
    

    三.打印详细的异常堆栈信息

    import datetime as dt
    import traceback as tb
    
    def read_date_from_file(filename):
        try:
            file = open(filename)
            in_date = file.read()
            in_date = in_date.strip()
            date = dt.datetime.strptime(in_date, '%Y-%m-%d')
            return date
        except (ValueError, OSError) as e:
            print('调用方法method1处理...')
            tb.print_exc()
    
    date = read_date_from_file('readme.txt')
    print('日期 = {0}'.format(date))
    

    注意不会报错,只会输出日志信息

    image.png

    四.自定义异常

    import datetime as dt
    
    class MyException(Exception):
        def __init__(self, message):
            super().__init__(message)
    
    def read_date_from_file(filename):
        try:
            file = open(filename)
            in_date = file.read()
            in_date = in_date.strip()
            date = dt.datetime.strptime(in_date, '%Y-%m-%d')
            return date
        except ValueError as e:
            raise MyException('不是有效的日期')
        except FileNotFoundError as e:
            raise MyException('文件找不到')
        except OSError as e:
            raise MyException('文件无法打开或无法读取')
    
    date = read_date_from_file('readme.txt')
    print('日期 = {0}'.format(date))
    
    image.png

    如果您发现本文对你有所帮助,如果您认为其他人也可能受益,请把它分享出去。

    相关文章

      网友评论

          本文标题:异常Exception

          本文链接:https://www.haomeiwen.com/subject/vpuonctx.html