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

        

        

  • 相关阅读:
    【转】 VC MFC 钩子 实现 自绘 窗体 标题栏 非客户区
    Scintilla开源库使用指南(二)
    Scintilla开源库使用指南(一)
    【转】MFC 多文档
    多视图识别
    获得MFC窗口其它类指针的方法
    sql2005 查看数据库或表大小的系统存储过程 sp_spaceused
    哪里是乐土?关于团队良性循环 (转)
    项目管理反思——前言
    项目经理思考——团队
  • 原文地址:https://www.cnblogs.com/venicid/p/7895001.html
Copyright © 2011-2022 走看看