zoukankan      html  css  js  c++  java
  • python学习-异常处理之捕获异常与抛出异常(七)

    捕获异常

    python完整的异常处理语法结构如下:

    特别说明:

    1.try块是必需的,except块和finally,当try块没有出现异常时,程序会执行else块

    2.try块后只有一个except快块会被执行,不可能有多个except块被执行。

    3.原则:先捕获小异常再捕获大异常

    实例:

    import sys
    
    try:
        a = int(sys.argv[1])
        b = int(sys.argv[2])
        c = a / b
        print("您输入的两个数相除的结果是:",c)
    except IndexError:
        print("索引错误:运行程序时输入的参数个数不够")
    except ValueError:
        print("数值错误:程序只能接受整数参数")
    except ArithmeticError:
        print("算术错误")
    except Exception:
        print("未知异常")
    
    # 输出结果:
    E:myprojcrazy_python77.2>python div_test.py 3 0
    算术错误
    单异常捕获
    import sys
    
    try:
        a = int(sys.argv[1])
        b = int(sys.argv[2])
        c = a / b
        print("您输入的两个数相除的结果是:",c)
    except (IndexError, ValueError, ArithmeticError):
        print("程序发生了数组越界、数字格式异常、算术异常之一")
    except:
        print("未知异常")
    
    # 输出结果
    E:myprojcrazy_python77.2>python multi_exception_test.py 4 0
    程序发生了数组越界、数字格式异常、算术异常之一
    多异常捕获
    def foo():
        try:
            fis = open("a.txt")
        except Exception as e:
            print(e)
            print(e.args)
            print(e.errno)
            print(e.strerror)
    
    
    foo()
    
    # 输出结果:
    [Errno 2] No such file or directory: 'a.txt'
    (2, 'No such file or directory')
    2
    No such file or directory
    访问异常信息

    4. 1try或except中的return语句,不会影响finally块的执行;但是os._exit()语句会退出python解释器,导致finally块试去执行机会。

    import os
    
    
    def test():
        fis = None
        try:
            fis = open("a.txt")
        except OSError as e:
            print(e.strerror)
            return
            os._exit(1)
        finally:
            if fis is not None:
                try:
                    fis.close()
                except OSError as ioe:
                    print(ioe.strerror)
            print("执行finally里的资源回收!")
    
    
    test()
    
    # 输出结果:
    No such file or directory
    执行finally里的资源回收!
    finally_1

    4.1不能在finally块使用return或raise。finally块中的return或raise语句,会导致try、except块中的return、raise语句失效

    def test():
        try:
            return True  # 由于finally中包含return,该return语句失效
        finally:
            return False
    
    
    a = test()
    print(a)
    
    # 输出结果
    False
    finally_2

    抛出异常(使用raise引发异常)

    不管是系统引发的异常,还是程序员使用raise手动引发的异常,python解释器对异常的处理没有任何差别,都可以使用try...except来捕获它

    raise语句有如下三种常用用法:

    def main():
        try:
            mtd(3)
        except Exception as e:
            print("程序出现异常:", e)
        mtd(3)
    
    
    def mtd(a):
        if a > 0:
            raise ValueError("a的值大于0.不符合要求")
    
    
    main()
    
    # 输出结果:
    D:softpython36python.exe D:/myproject/crazy_python/07/7.3/raise_test.py
    Traceback (most recent call last):
    程序出现异常: a的值大于0.不符合要求
      File "D:/myproject/crazy_python/07/7.3/raise_test.py", line 17, in <module>
        main()
      File "D:/myproject/crazy_python/07/7.3/raise_test.py", line 9, in main
        mtd(3)
      File "D:/myproject/crazy_python/07/7.3/raise_test.py", line 14, in mtd
        raise ValueError("a的值大于0.不符合要求")
    ValueError: a的值大于0.不符合要求
    raise_1

    except和raise同时使用

    class AuctionException(Exception): pass
    class AuctionTest:
        def __init__(self, init_price):
            self.init_price = init_price
        def bid(self, bid_price):
            d = 0.0
            try:
                d = float(bid_price)
            except Exception as e:
                # 此处只是简单地打印异常信息
                print("转换出异常:", e)
                # 再次引发自定义异常
    #            raise AuctionException("竞拍价必须是数值,不能包含其他字符!")  # ①
                raise AuctionException(e)
            if self.init_price > d:
                raise AuctionException("竞拍价比起拍价低,不允许竞拍!")
            initPrice = d
    def main():
        at = AuctionTest(20.4)
        try:
            at.bid("df")
        except AuctionException as ae:
            # 再次捕获到bid()方法中的异常,并对该异常进行处理
            print('main函数捕捉的异常:', ae)
    main()
    
    # 输出结果:
    转换出异常: could not convert string to float: 'df'
    main函数捕捉的异常: could not convert string to float: 'df'
    except_raise
  • 相关阅读:
    Mongodb 查询时间类型
    Python更新所有pip package
    Python selenium on windows
    Redis cluster setup on windows
    CAP定理(theorem)
    error: Microsoft Visual C++ 14.0 is required when installing python package
    using RNGCryptoServiceProvider to generate random string
    <map>的使用
    二维vector的使用
    vector做形参时的三种传参方式
  • 原文地址:https://www.cnblogs.com/wang-mengmeng/p/11509688.html
Copyright © 2011-2022 走看看