zoukankan      html  css  js  c++  java
  • day 2 异常传递 ,抛出

    1.异常的传递

    def test1():
        print("---test1--")
        print(num)
        print('---test1 over---')
    
    def test2():
        print('---test2---')
        test1()
        print('----test2 over ----')
    
    def test3():
        try:
            print('----test3---')
            test2()
            print('----test3 ovrer')
        except Exception as result:
            print("捕获到了异常,异常时%s"%result)
    
    test3()
    ----test3---
    ---test2---
    ---test1--
    捕获到了异常,异常时name 'num' is not defined

    2.抛出自定义异常

      自定义个异常类,继承Exception

    class ShortInputException(Exception):
        '''自定义的异常类'''
        def __init__(self, length, atleast):
            #super().__init__()
            self.length = length
            self.atleast = atleast
    
    def main():
        try:
            s = input('请输入 --> ')
            if len(s) < 3:
                # raise引发一个你定义的异常
                raise ShortInputException(len(s), 3)
        except ShortInputException as result:#x这个变量被绑定到了错误的实例
            print('ShortInputException: 输入的长度是 %d,长度至少应是 %d'% (result.length, result.atleast))
        else:
            print('没有异常发生.')
    
    main()

     

    3.异常处理中抛出异常

    class Test(object):
        def __init__(self, switch):
            self.switch = switch #开关
        def calc(self, a, b):
            try:
                return a/b
            except Exception as result:
                if self.switch:
                    print("捕获开启,已经捕获到了异常,信息如下:")
                    print(result)
                else:
                    #重新抛出这个异常,此时就不会被这个异常处理给捕获到,从而触发默认的异常处理
                    raise
    
    
    a = Test(True)
    a.calc(11,0)
    
    print("----------------------华丽的分割线----------------")
    
    a.switch = False
    a.calc(11,0)

        

        

     4.if真假判断

        

        

  • 相关阅读:
    LevelDB的源码阅读(四) Compaction操作
    LevelDB的源码阅读(三) Get操作
    LevelDB的源码阅读(三) Put操作
    高级测试/测试开发技能
    IM测试功能点
    深入理解--SSM框架中Dao层,Mapper层,controller层,service层,model层,entity层都有什么作用
    Jmeter非GUI分布式测试
    全套支付宝系统架构(内部架构图)【收藏】
    Jmeter
    报表类相关测试范围总结
  • 原文地址:https://www.cnblogs.com/venicid/p/7895001.html
Copyright © 2011-2022 走看看