1、处理指定类型的异常(代码出现错误,解释器会中断当前模块代码的执行)
print(“开始执行**”)
try:
asfdsafd
print(“hellowrd”)
5 / 0
except NameError:
print(“NameError”)
print(“代码结束**”)
2、捕获指定多种异常的类型
print(“开始执行**”)
try:
print(“hellowrd”)
5 / 1
似懂非懂
except NameError:
print(“NameError”)
except ZeroDivisionError:
print(“ZeroDivisionError”)
print(“代码结束**”)
3、获取异常的详细信息
print(“开始执行**”)
try:
print(“hellowrd”)
5 / 1
似懂非懂
except NameError as e:
print(“NameError:”,e)
except ZeroDivisionError as e:
print(“ZeroDivisionError:”,e)
print(“代码结束**”)
4、捕获任意类型异常
import traceback
print(“开始”)
try:
asdfsad
except Exception: Exception捕获所有的异常类型
print(“捕获所有异常”)
print(“结束”)
finallys是我代码不管有没有异常都会执行
else出现异常不会执行,
print(“开始”)
try:
dsfdsg
except: except简写捕获所有异常类型等价于except Exception
print(“捕获所有异常”,traceback.format_exc())
else:
print(“这是else”)
finally:
print(“这是finally”)
print(“结束”)
5、举例一
def f1():
try:
print(“这是f1”)
5 / 0
print(“f1结束”)
except:
print(“这是f1的异常被捕获了”)
def f2():
try:
print(“这是f2”)
f1()
print(“f1执行结束”)
except:
print(“这是f2的异常被捕获了”)
def f3():
try:
print(“这是f3”)
f2()
print(“f3执行结束”)
except:
print(“这是f3的异常被捕获了”)
f3()
6、举例二
def f1():
try:
print(“这是f1”)
5 / 0
print(“f1结束”)
except:
raise(#抛出异常)
def f2():
try:
print(“这是f2”)
f1()
print(“f1执行结束”)
except:
raise
def f3():
try:
print(“这是f3”)
f2()
print(“f3执行结束”)
except:
print(“这是f3的异常被捕获了”)
f3()