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

        

        

  • 相关阅读:
    sleep(),wait(),yield(),notify()
    (三)终结任务
    (二)共享受限资源
    (一)基本的线程机制
    (十八)多线程
    (十七)泛型程序设计
    视频监控中带宽及存储容量的计算
    turtle实例
    python ——钟表
    Python Tkinter Grid布局管理器详解
  • 原文地址:https://www.cnblogs.com/venicid/p/7895001.html
Copyright © 2020-2023  润新知