文章目录 [ 隐藏 ]
Python3 异常
作为Python初学者,在刚学习Python编程时,经常会看到一些报错信息,在前面我们没有提及,这章节我们会专门介绍。
下面列出几个常见的异常,大家只要大致扫一眼,有个映像即可。
异常 | 描述 |
---|---|
NameError | 尝试访问一个没有申明的变量 |
ZeroDivisionError | 除数为0 |
SyntaxError | 语法错误 |
IndexError | 索引超出序列范围 |
KeyError | 请求一个不存在的字典关键字 |
IOError | 输入输出错误(比如你要读的文件不存在) |
AttributeError | 尝试访问未知的对象属性 |
ValueError | 传给函数的参数类型不正确,比如给int()函数传入字符串形 |
2.异常捕获的语法
标准语法:
1 2 3 4 5 6 7 8 9 |
try: try_suite except Exception1,Exception2,...,Argument as e: exception_suite ...... #other exception block else: no_exceptions_detected_suite finally: always_execute_suite |
2.1 try..except
try_suite不消我说大家也知道,是我们需要进行捕获异常的代码。而except语句是关键,我们try捕获了代码段try_suite里的异常后,将交给except来处理。
try…except语句最简单的形式如下:
1 2 3 4 |
try: try_suite except: exception block |
或者
1 2 3 4 |
try: try_suite except Exception as e: exception block |
举个列子
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
try: lines=open(tfile,'r',encoding='utf-8').readlines() flen=len(lines)-1 for i in range(flen): if sstr in lines[i]: lines[i]=lines[i].replace(sstr,rstr) open(tfile,'w').writelines(lines) print('修改文件内容为:'+rstr) except IOError: print('输入输出异常') except AttributeError: print('尝试访问未定义的属性') except Exception as e: print(e) print('打开失败了') |
2.2try … except…else语句
没有检测到异常的时候,则执行else语句。举个例子大家可能更明白些:
1 2 3 4 5 6 7 8 9 |
>>> import syslog >>> try: ... f = open("/root/test.py") ... except IOError,e: ... syslog.syslog(syslog.LOG_ERR,"%s"%e) ... else: ... syslog.syslog(syslog.LOG_INFO,"no exception caught\n") ... >>> f.close() |
2.3 finally子句
finally子句是无论是否检测到异常,都会执行的一段代码。我们可以丢掉except子句和else子句,单独使用try…finally,也可以配合except等使用
介绍一个特殊的处理异常的简便方法
断言(assert)
什么是断言,先看语法:
1 |
assert expression[,reason] |
其中assert是断言的关键字。执行该语句的时候,先判断表达式expression,如果表达式为真,则什么都不做;如果表达式不为真,则抛出异常。reason跟我们之前谈到的异常类的实例一样。不懂?没关系,举例子!最实在!
1 2 3 4 5 6 |
>>> assert len('love') == len('like') >>> assert 1==1 >>> assert 1==2,"1 is not equal 2!" Traceback (most recent call last): File "<stdin>", line 1, in <module> AssertionError: 1 is not equal 2! |
assert后面的表达式为真,则什么都不做,如果不为真,就会抛出AssertionErro异常,而且我们传进去的字符串会作为异常类的实例的具体信息存在。其实,assert异常也可以被try块捕获
1 2 3 4 5 6 7 8 |
>>> try: ... assert 1 == 2 , "1 is not equal 2!" ... except AssertionError,reason: ... print "%s:%s"%(reason.__class__.__name__,reason) ... AssertionError:1 is not equal 2! >>> type(reason) <type 'exceptions.AssertionError'> |
未经允许不得转载:Python在线学习 » 【第十八节】Python错误和异常