isinstance和issubclass、动态模块导入、异常处理
<table style="height: 30px; background-color: #afeeee; width: 1266px;" border="0"> |
在coding过程中,运行是或多或少都会出现异常,代码出异常后会自动停止,异常处理显得格外的重要,python中异常处理采用了try和except实现,如果捕捉到了异常代码会继续往下执行而不会报错,基本语法如下:
例如:
?2.一次捕获多个异常
如果代码中需要存在多个异常,捕获多个异常的时候,只要第一个异常捕获到了,try中的代码将不会执行,方法有两种:
- 多个except
my_list[</span>10]=1<span style="color: #000000;">
int(a)
<span style="color: #0000ff;">except<span style="color: #000000;"> ValueError as e:<span style="color: #0000ff;">print<span style="color: #000000;">(e)
<span style="color: #0000ff;">print(<span style="color: #800000;">'<span style="color: #800000;">走到了Value Error<span style="color: #800000;">'<span style="color: #000000;">)
<span style="color: #0000ff;">except<span style="color: #000000;"> IndexError as e:
<span style="color: #0000ff;">print<span style="color: #000000;">(e)
<span style="color: #0000ff;">print(<span style="color: #800000;">'<span style="color: #800000;">走到了Index Error<span style="color: #800000;">'<span style="color: #000000;">)
<span style="color: #008000;">#<span style="color: #008000;">异常不会有顺序,只要第一次的捕获到了,try语句中的代码将不会执行,转而执行except下面代码结果:
list assignment index out of range走到了Index Error
- 一个except中写多个异常。
my_list[</span>10]=1<span style="color: #000000;">
int(a)
<span style="color: #0000ff;">except<span style="color: #000000;"> (ValueError,IndexError) as e:<span style="color: #0000ff;">print<span style="color: #000000;">(e)
<span style="color: #0000ff;">print(<span style="color: #800000;">'<span style="color: #800000;">走到了这里<span style="color: #800000;">'<span style="color: #000000;">) <span style="color: #008000;">#<span style="color: #008000;">异常不会有顺序,只要第一次的捕获到了,try语句中的代码将不会执行,转而执行except下面代码
<span style="color: #000000;">结果:
list assignment index out of range
走到了这里
3.捕获绝大多数异常(Execption)
Execption中包含了所有的python中自带的异常,但并不能捕捉类似与语法错误,缩进错误的异常。
my_list[</span>10]=1<span style="color: #000000;">
int(a)
<span style="color: #0000ff;">except<span style="color: #000000;"> Exception as e:<span style="color: #0000ff;">print<span style="color: #000000;">(e)
<span style="color: #0000ff;">print(<span style="color: #800000;">'<span style="color: #800000;">走到了这里<span style="color: #800000;">'<span style="color: #000000;">)
结果:
list assignment index out of range
走到了这里
4.主动触发异常(raise)
5.自定义异常与异常详情
在进行软件开发的过程中,往往会引入第三方模块,此时的异常并不是标准的异常,所以我们需要自己定义异常,并捕获。
Exception类与BaseException类
Exception类是BaseException类的子类,从源码中可以看到,Exception类中主要有两种方法用于异常处理,即
1.__init__()构造方法,用于实例化异常,参数为获取异常内容。
2.__str__()方法,我们知道该方法一般用于print打印。
6.try,except其他语法结构
7.异常处理--断言
assert即断言,也用于异常处理,有些时候在某些特定的场景发挥优雅的作用。
语法:
<div class="cnblogs_code">
name=
name==
(,line 21,
name==
(编辑:李大同)
【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!