首页 Python python学习笔记十:异常

python学习笔记十:异常

一、语法#!/usr/bin/pythonfilename=hello#try except finally demotry:open(abc.txt)print helloexcept IOError,msg:print the file not existexcept NameError,msg:print hello not definedfinally:print end#throw exceptionif filename == hello:raise Ty

一、语法

filename=

<span style=”color: #008000;”>#<span style=”color: #008000;”>try except finally demo
<span style=”color: #0000ff;”>try<span style=”color: #000000;”>:
open(<span style=”color: #800000;”>'<span style=”color: #800000;”>abc.txt<span style=”color: #800000;”>'<span style=”color: #000000;”>)
<span style=”color: #0000ff;”>print<span style=”color: #000000;”> hello
<span style=”color: #0000ff;”>except<span style=”color: #000000;”> IOError,msg:
<span style=”color: #0000ff;”>print <span style=”color: #800000;”>'<span style=”color: #800000;”>the file not exist<span style=”color: #800000;”>’
<span style=”color: #0000ff;”>except<span style=”color: #000000;”> NameError,msg:
<span style=”color: #0000ff;”>print <span style=”color: #800000;”>'<span style=”color: #800000;”>hello not defined<span style=”color: #800000;”>’
<span style=”color: #0000ff;”>finally<span style=”color: #000000;”>:
<span style=”color: #0000ff;”>print <span style=”color: #800000;”>'<span style=”color: #800000;”>end<span style=”color: #800000;”>’

<span style=”color: #008000;”>#<span style=”color: #008000;”>throw exception
<span style=”color: #0000ff;”>if filename == <span style=”color: #800000;”>”<span style=”color: #800000;”>hello<span style=”color: #800000;”>”<span style=”color: #000000;”>:
<span style=”color: #0000ff;”>raise TypeError(<span style=”color: #800000;”>'<span style=”color: #800000;”>nothing<span style=”color: #800000;”>’)

二、常见异常类型

1、AssertionError:assert语句失败

2、AttributeError:试图访问一个对象没有的属性

3、IOError:输入输出异常,基本是无法打开文件

4、ImportError:无法引入模块或者包,基本是路径问题

5、IndentationError:语法错误,代码没有正确对齐

6、IndexError:下标索引超出序列边界

7、KeyError:试图访问你字典里不存在的键

8、KeyboardInterrupt:Ctrl+C被按下

9、NameError:使用一个还声明的变量

10、SyntaxError:代码逻辑语法出错,不能执行

12、TypeError:传入的对象类型与要求不符

13、UnboundLocalError:试图问一个还未设置的全局变量,基本上是由于另有一个同名的全局变量

14、ValueError:传入一个不被期望的值,即使类型正确

本文来自网络,不代表青岛站长网立场。转载请注明出处: https://www.0532zz.com/html/kaifa/python/20200723/7123.html
上一篇
下一篇

作者: dawei

【声明】:青岛站长网内容转载自互联网,其相关言论仅代表作者个人观点绝非权威,不代表本站立场。如您发现内容存在版权问题,请提交相关链接至邮箱:bqsm@foxmail.com,我们将及时予以处理。

为您推荐

返回顶部