• 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真假判断

        

        

  • 相关阅读:
    Nightwatch的介绍
    reduce的用法及实例
    什么是声明式渲染?
    H5自带的表单验证
    Flex弹性布局
    JS中的forEach,for in,for of和for的遍历优缺点及区别
    将博客搬至CSDN
    9 外观模式(Facade)
    8 代理模式(Proxy)
    7 装饰模式(Decorator)
  • 原文地址:https://www.cnblogs.com/venicid/p/7895001.html
Copyright © 2020-2023  润新知