首页 > 其他分享 >try except except finally

try except except finally

时间:2023-12-28 19:58:45浏览次数:23  
标签:... end except try test finally Initializing print return

import traceback
import time


class A(object):
    def __init__(self):
        print(f'Initializing {self.__class__.__name__}')
    def __del__(self):
        print(f'Releasing {self.__class__.__name__}')
        
class B(A):
    pass

def tt(func, li):
    b = B()
    print('run tt  111 ...')
    for n in li:
        print(func(n))
    print('run tt  222 ...')
    return 'CCCCCC'

def test(n):
    a = A()
    try:
        x = 100/n
        print(n, x)
        time.sleep(2)
    except Exception:
        print('Exception')
        print(traceback.format_exc())
        print('Exception go ...')
        return 'abnormal end from Exception in test...'
        # 因为test是一个函数, 函数一定会有返回值, 这个默认有 return None
    except KeyboardInterrupt: # 如果except捕获了KeyboardInterrupt异常,那么执行except KeyboardInterrupt:语句块,当执行到exit(2)语句时,解释器会把finally:语句块先执行完,然后释放资源, 然后退出程序前,打印Process finished with exit code 1到标准输出,      print('exit 2')语句和print('End...')是执行不到了
        print('KeyboardInterrupt')
        print(traceback.format_exc())
        print('KeyboardInterrupt go ...')
        exit(2)
        print('exit 2')
        # 因为test是一个函数, 函数一定会有返回值, 这个默认有 return None
    finally:
        print('finally')
    print('normal end before return...')
    return 'normal end from test...'  # 如果没有捕获到任何异常,那么函数执行到return 语句时,会先释放函数内的变量标识符(如果引用对象计数是1,那么解释器垃圾回收机制会释放标识符引用的对象),然后return 返回.
    
if __name__ == '__main__':
    li = [1, 2, 0, 3, 0, 5]
    print(tt(test, li))
    print('End...')
    

Initializing B
run tt 111 ...
Initializing A
1 100.0
finally
normal end before return...
Releasing A
normal end from test...
Initializing A
2 50.0
finally
normal end before return...
Releasing A
normal end from test...
Initializing A
Exception
Traceback (most recent call last):
File "C:\Git_pro\ttttttttttttttttttttttttt\test.py", line 25, in test
x = 100/n
ZeroDivisionError: division by zero

Exception go ...
finally
Releasing A
abnormal end from Exception in test...
Initializing A
3 33.333333333333336
finally
normal end before return...
Releasing A
normal end from test...
Initializing A
Exception
Traceback (most recent call last):
File "C:\Git_pro\ttttttttttttttttttttttttt\test.py", line 25, in test
x = 100/n
ZeroDivisionError: division by zero

Exception go ...
finally
Releasing A
abnormal end from Exception in test...
Initializing A
5 20.0
finally
normal end before return...
Releasing A
normal end from test...
run tt 222 ...
Releasing B
CCCCCC
End...

Process finished with exit code 0

 

----------------------------------在迭代列表中的第二元素后,在time.sleep(2)中, 执行Ctrl + C, 触发KeyboardInterrupt异常 如下:

Initializing B
run tt 111 ...
Initializing A
1 100.0
finally
normal end before return...
Releasing A
normal end from test...
Initializing A
2 50.0
KeyboardInterrupt
Traceback (most recent call last):
File "C:\Git_pro\Clone\cloudperformancetest\XGS\ooklatool\test.py", line 27, in test
time.sleep(2)
KeyboardInterrupt

KeyboardInterrupt go ...
finally
Releasing A
Releasing B

Process finished with exit code 2

 

标签:...,end,except,try,test,finally,Initializing,print,return
From: https://www.cnblogs.com/zfplost/p/17933432.html

相关文章

  • 信阳 信阳农林学院 Xinyang Agriculture and Forestry University 简 称信阳农林
    信阳农林学院外文名XinyangAgricultureandForestryUniversity简    称信阳农林·XinyangA&FUniversity(XYAFU) 历史沿革1910年(清宣统二年)学校在私立淮西中等学堂旧址(今汝南县城关)创建,校名为汝宁府中等实业学堂。1911年改称汝宁府官立甲种农业学校。1......
  • Sqoop连接数据库报错:Caused by: javax.net.ssl.SSLHandshakeException: No appropriat
    控制台报错:[[email protected]__hadoop-2.0.0-alpha]#./bin/sqooplist-databases--connectjdbc:mysql://192.168.45.10:3306--usernameroot--password1234562023-12-2802:58:50,807WARNtool.BaseSqoopTool:Settingyourpasswordonthecommand-linei......
  • 记录--try...catch知识补全
    这里给大家分享我在网上总结出来的一些知识,希望对大家有所帮助说到try...catch都觉得非常熟悉了,不就是用来捕捉代码块中的错误嘛,平时也用得比较多的。然而因为了解不够多,我的面试却栽在了一个简单的知识点上:try...catch只能捕捉到同步执行代码块中的错误。题目是:以下代码有错......
  • Spring Boot学习随笔- 后端实现全局异常处理(HandlerExceptionResolver),前后端解决跨域
    学习视频:【编程不良人】2021年SpringBoot最新最全教程第十七章、异常处理异常处理作用:用来解决整合系统中任意一个控制器抛出异常时的统一处理入口传统方式传统单体架构下的处理方式配置全局异常处理类@ComponentpublicclassGlobalExceptionResolverimplementsHand......
  • java.net.MalformedURLException: no protocol异常处理
    摘要:本篇博客讨论了Java应用程序中可能遇到的java.net.MalformedURLException:noprotocol异常,并提供了解决方案。我们首先介绍了该异常的错误信息和可能的原因,然后提供了两种解决方案,一种是确保URL包含正确的通信协议,另一种是通过URL编码和解码来处理特殊字符和编码问题。我们......
  • debug跳转至 var4.getTargetException()
    今天敲了一个插入表的业务逻辑,发现控制台没有报错,但方法却没有执行完毕,debug后发现程序跳转到了该异常。经过上网搜索后有所了解,出现该异常的根本原因是当使用反射调用方法时,如果被调用的方法抛出了异常,而调用的方法却没有捕捉处理,那么该异常会被封装在一个`InvocationTargetEx......
  • js一道try...catch的面试题
    说到try...catch都觉得非常熟悉了,不就是用来捕捉代码块中的错误嘛,平时也用得比较多的。然而因为了解不够多,我的面试却栽在了一个简单的知识点上:try...catch只能捕捉到同步执行代码块中的错误。题目是:以下代码有错吗?如果有错,应该如何改正?try{setTimeout(()=>{thrown......
  • nested exception is org.apache.ibatis.type.TypeException: Could not set paramete
    org.mybatis.spring.MyBatisSystemException:nestedexceptionisorg.apache.ibatis.type.TypeException:Couldnotsetparametersformapping:ParameterMapping{property='name',mode=IN,javaType=classjava.lang.String,jdbcType=null,numericScale=nu......
  • 37. 干货系列从零用Rust编写负载均衡及代理,负载均衡中try_files实现
    wmproxywmproxy已用Rust实现http/https代理,socks5代理,反向代理,静态文件服务器,四层TCP/UDP转发,七层负载均衡,内网穿透,后续将实现websocket代理等,会将实现过程分享出来,感兴趣的可以一起造个轮子项目地址国内:https://gitee.com/tickbh/wmproxygithub:https://github.com/......
  • webpack(入口起点entry 和 输出output)
    单个入口(简写)语法//单个入口,简写,字符串module.exports={entry:'./path/to/my/entry/file.js',};上面是单个入口的语法,是下面的简写://单个入口,完整,对象类型module.exports={entry:{main:'./path/to/my/entry/file.js',},};//多个入口,数组。outpu......