Python自动化学习--异常提示
举例:打开一个不存在的文件时:
>>open("abc.txt","r")
会提示错误
traceback (most recent call last):
file "d:/project1/test.py", line 11, in <module>
open("abc.txt","r")
filenotfounderror: [errno 2] no such file or directory: 'abc.txt'
这时可以用 try....except 语句来捕捉并处理这个异常
try:
open("abc.txt","r")
except filenotfounderror:
print("出错啦")
----------------------
这时运行就只会打印“出错啦”
如果将语句换成:
try:
print(a)
except filenotfounderror:
print("出错啦")
----------------------
traceback (most recent call last):
file "d:/project1/test.py", line 12, in <module>
print(a)
nameerror: name 'a' is not defined
运行时还是报错了,这时因为“filenotfounderror”是表示找不到文件时的报错,跟现在的“nameerror”不符,所以代码改成如下所示就行了:
try:
print(a)
except nameerror:
print("出错啦")
但是,在python中,所有的异常都继承于exception,自2.5版本之后,出现的新的基类baseexception,新的基类可以接收所有的异常:
try:
print(a)
open("abc.txt","r")
except baseexception:
print("出错啦")
-------------------------
不管那一行出现异常,都能捕捉到并打印“出错啦”,但是并不能知道哪一行的语句出错,这时我们可以打印异常信息:
try:
print(a)
open("abc.txt","r")
except baseexception as msg:
print(msg)
print("出错啦")
-------------------------
[errno 2] no such file or directory: 'abc.txt'
以下列出python中常见的异常:
baseexception | 新的所有异常类的基类 |
exception | 所有异常的基类,但继承自baseexception |
assertionerror | asser语句失败 |
filenotfounderror | 试图打开一个不存的文件或目录 |
attributeerror | 试图访问的对象没有属性 |
oserror | 当系统函数返回一个系统相关的错误(包括i/o故障),如“找不到文件”或“磁盘已满”时,引发此异常 |
nameerror | 使用一个还未赋值对象的变量 |
indexerror | 当一个序列超出范围时引发此异常 |
syntaxerror | 当解析器遇到一个语法错误时引发此异常 |
keyboardinterrupt | 组合键ctrl+c被按下,程序被强制终止 |
typeerror | 传入的对象类型与要求不符 |
异常结合else的用法:
try:
a ="异常测试:"
print(a)
except nameerror as msg:
print(msg)
esle:
print("没有异常时执行")
------------------------------
当出现异常时,打印异常信息“msg”,当没有异常时,执行esle,打印“没有异常时执行”
异常结合finallyd的用法:
try:
print(a)
except nameerror as msg:
print(msg)
finally:
print("不管有无异常,都执行finally)
用户自定义的异常抛出 raise:
class loogexcept(exception):
def __init__(self,leng):
self.leng = leng
def __str__(self):
print("你的名字:"+str(self.leng)+",超过长度啦!")
def name_test():
try:
name = input("enter your name:")
if len(name) > 4:
raise loogexcept(len(name))
else:
print(name)
except loogexcept as e_result:
print("捕捉到异常啦")
print("打印异常:",e_result)
if __name__ == "__main__":
name_test()
---------------------------------------------
enter your name:sadsadasd
捕捉到异常啦
打印异常: 你的名字:9,超过长度啦!
你的名字:9,超过长度啦!
traceback (most recent call last):
file "d:/project1/test.py", line 19, in name_test
raise loogexcept(len(name))
__main__.loogexcept: <exception str() failed>
during handling of the above exception, another exception occurred:
traceback (most recent call last):
file "d:/project1/test.py", line 27, in <module>
name_test()
file "d:/project1/test.py", line 24, in name_test
print("打印异常:",e_result)
typeerror: __str__ returned non-string (type nonetype)
process finished with exit code 1