python嵌套try...except如何使用详解

作者:youhebuke225 时间:2022-06-21 16:53:00 

引言

众所周知,在python中我们用try…except…来捕获异常,使用raise来抛出异常,但是多重的try…except…是如何使用的呢

前提

抛出异常

当调用raise进行抛出错误的时候,抛出错误的后面的代码不执行

def func():
   print("hello")
   raise Exception("出现了错误")
   print("world")

func()

打印的错误堆栈

如果抓取错误,就相当于if...else,并不会打断代码的执行

def func():
   try:
       print("hello")
       raise Exception("出现了错误")
   except Exception as why:
       print(why)
       print("world")

func()

自定义异常

自定义异常需要我们继承异常的类,包括一些框架中的异常的类,我们自定义异常的话都需要继承他们

class MyError(Exception):
   pass

def say_hello(str):
   if str != "hello":
       raise MyError("传入的字符串不是hello")
   print("hello")

say_hello("world")

异常对象

  • Exception 是多有异常的父类,他会捕获所有的异常

  • 其后面会跟一个as as后面的变量就是异常对象,异常对象是异常类实例化后得到的

多重try

如果是嵌套的try...except...的话,这一层raise的错误,会被上一层的try...except...进行捕获

补充:捕获异常的小方法

方法一:捕获所有异常

a=10
b=0
try:
   print (a/b)
except Exception as e:
   print(Exception,":",e)
finally:
   print ("always excute")

运行:

<class 'Exception'> : division by zero
always excute

方法二:采用traceback模块查看异常

import traceback  
try:
   print ('here1:',5/2)
   print ('here2:',10/5)
   print ('here3:',10/0)

except Exception as e:
   traceback.print_exc()

运行:

here1: 2.5
here2: 2.0
Traceback (most recent call last):
  File "/Users/lilong/Desktop/online_release/try_except_use.py", line 59, in <module>
    print ('here3:',10/0)
ZeroDivisionError: division by zero

方法三:采用sys模块回溯最后的异常

import sys  
try:
   print ('here1:',5/2)
   print ('here2:',10/5)
   print ('here3:',10/0)

except Exception as e:
   info=sys.exc_info()  
   print (info[0],":",info[1])

运行:

here1: 2.5
here2: 2.0
<class 'ZeroDivisionError'> : division by zero

注意:万能异常Exception

被检测的代码块抛出的异常有多种可能性,并且我们针对所有的异常类型都只用一种处理逻辑就可以了,那就使用Exception,除非要对每一特殊异常进行特殊处理。

来源:https://blog.csdn.net/youhebuke225/article/details/124365365

标签:try,except,嵌套
0
投稿

猜你喜欢

  • FrontPage服务器扩展

    2008-03-05 13:05:00
  • php+mysqli实现批量替换数据库表前缀的方法

    2023-11-22 10:15:55
  • Python网页解析利器BeautifulSoup安装使用介绍

    2021-06-12 05:00:00
  • 教你在SQL Server 2000数据库中使用分区

    2008-11-25 11:55:00
  • 详解Python函数print用法

    2023-06-10 03:47:34
  • 详解Python3 对象组合zip()和回退方式*zip

    2021-03-01 11:14:09
  • python编程-将Python程序转化为可执行程序[整理]

    2022-10-28 03:48:43
  • Python与Appium实现手机APP自动化测试的示例代码

    2023-07-26 05:06:07
  • asp base64 utf-8为了兼容asp.net的base64

    2011-03-10 10:47:00
  • python 利用PyAutoGUI快速构建自动化操作脚本

    2021-08-04 15:42:14
  • python多进程使用apply_async的使用方法详解

    2022-11-14 16:08:50
  • 利用Python写个简易版星空大战游戏

    2023-08-26 14:07:42
  • 使用Python脚本生成随机IP的简单方法

    2023-12-30 06:46:28
  • 解决django无法访问本地static文件(js,css,img)网页里js,cs都加载不了

    2023-06-13 19:13:36
  • 有关缓存 Cache 的随想

    2008-06-09 14:25:00
  • Python机器视觉之基于OpenCV的手势检测

    2021-06-12 10:54:11
  • python查看模块,对象的函数方法

    2021-07-11 19:45:10
  • NumPy迭代数组的实现

    2022-01-03 14:07:37
  • 在 CSS 中关于字体处理效果的思考

    2008-04-25 22:57:00
  • Python中函数的多种格式和使用实例及小技巧

    2022-12-18 10:22:32
  • asp之家 网络编程 m.aspxhome.com