总的来说,编写程序时遇到的错误可大致分为 2 类,分别为语法错误和运行时错误。
>>> print'aaa'
File "", line 1
print'aaa'
^
SyntaxError: invalid syntax #语法错误
>>> a = 1/0
Traceback (most recent call last):
File "", line 1, in
ZeroDivisionError: division by zero #运行时错误
>>>
表 1 Python常见异常类型
异常类型含义实例
AssertionError
当 assert 关键字后的条件为假时,程序运行会停止并抛出 AssertionError 异常
>>> demo_list = ['C语言中文网']
>>> assert len(demo_list) > 0
>>> demo_list.pop()
'C语言中文网'
>>> assert len(demo_list) > 0
Traceback (most recent call last):
File "", line 1, in
assert len(demo_list) > 0
AssertionError
AttributeError
当试图访问的对象属性不存在时抛出的异常
>>> demo_list = ['C语言中文网']
>>> demo_list.len
Traceback (most recent call last):
File "", line 1, in
demo_list.len
AttributeError: 'list' object has no attribute 'len'
IndexError
索引超出序列范围会引发此异常
>>> demo_list = ['C语言中文网']
>>> demo_list[3]
Traceback (most recent call last):
File "", line 1, in
demo_list[3]
IndexError: list index out of range
KeyError
字典中查找一个不存在的关键字时引发此异常
>>> demo_dict={'C语言中文网':"c.biancheng.net"}
>>> demo_dict["C语言"]
Traceback (most recent call last):
File "", line 1, in
demo_dict["C语言"]
KeyError: 'C语言'
NameError
尝试访问一个未声明的变量时,引发此异常
>>> C语言中文网
Traceback (most recent call last):
File "", line 1, in
C语言中文网
NameError: name 'C语言中文网' is not defined
TypeError
不同类型数据之间的无效操作
>>> 1+'C语言中文网'
Traceback (most recent call last):
File "", line 1, in
1+'C语言中文网'
TypeError: unsupported operand type(s) for +: 'int' and 'str'
ZeroDivisionError
除法运算中除数为 0 引发此异常
>>> a = 1/0
Traceback (most recent call last):
File "", line 1, in
a = 1/0
ZeroDivisionError: division by zero
提示:表中的异常类型不需要记住,只需简单了解即可。
Python try except异常处理详解
Python 提供了try except语句捕获并处理异常,该异常处理语句的基本语法结构如下:
try:
可能产生异常的代码块
except [(Error1, Error2, ...) [as e]]:
处理异常的代码块1
except [(Error3, Error4, ...) [as e]]:
处理异常的代码块2
try except 语句的执行流程如下:
首先执行 try 中的代码块,如果执行过程中出现异常,系统会自动生成一个异常对象,该异常对象会提交给 Python 解释器,此过程被称为引发异常。
当 Python 解释器收到异常对象时,会寻找能处理该异常对象的 except 块,如果找到合适的 except 块,则把该异常对象交给该 except 块处理,这个过程被称为捕获异常。如果 Python 解释器找不到捕获异常的 except 块,则程序运行终止,Python 解释器也将退出。
[root@kube try]# cat demo.py
#coding:utf-8
try: #try 代码块用于引发异常
a = int(input('输入被除数:'))
b = int(input('输入除数:'))
c = a / b
except(ValueError, ArithmeticError): #捕获异常,处理异常
print('您输入的数值有误,只接受正整数')
except: #未指定异常类型,表示所有异常
print('未定义异常')
print(' 继续执行' )
[root@kube try]#
[root@kube try]# py demo.py
输入被除数:3
输入除数:3
继续执行
[root@kube try]# py demo.py
输入被除数:a
您输入的数值有误,只接受正整数
继续执行
[root@kube try]# py demo.py
输入被除数:4
输入除数:0
您输入的数值有误,只接受正整数
继续执行
访问异常信息
如果程序需要在 except 块中访问异常对象的相关信息,可以通过为 except 块添加as a来实现。当 Python 解释器决定调用某个 except 块来处理该异常对象时,会将异常对象赋值给 except 块后的异常变量,程序即可通过该变量来获得异常对象的相关信息。
所有的异常对象都包含了如下几个常用属性和方法:
args:该属性返回异常的错误编号和描述字符串。
errno:该属性返回异常的错误编号。
strerror:该属性返回异常的描述宇符串。
with_traceback():通过该方法可处理异常的传播轨迹信息。
标签:Python,demo,list,except,C语言,try,机制,异常
来源: https://www.cnblogs.com/zy09/p/11699663.html