# -*- coding: UTF-8 -*-
try:
fh = open("a.txt",‘w‘)
fh.write("This is a file for Exception test!")
except IOError:
print "Error, file not found or access failure!"
else:
print "Successful!"
输出:
helloworld@LG-virtual-machine:~/code$ python test.py
Successful!
helloworld@LG-virtual-machine:~/code$ cat a.txt
This is a file for Exception test!helloworld@LG-virtu
write()
是不加换行符的chmod -w a.txt
helloworld@LG-virtual-machine:~/code$ python test.py
Error, file not found or access failure!
try:
正常的操作
......................
except:
发生异常,执行这块代码
......................
else:
如果没有异常执行这块代码
try:
正常的操作
......................
except(Exception1[, Exception2[,...ExceptionN]]]):
发生以上多个异常中的一个,执行这块代码
......................
else:
如果没有异常执行这块代码
# -*- coding: UTF-8 -*-
try:
fh = open("a.txt",‘w‘)
fh.write("This is a file for Exception test!")
finally:
print "Error: File not found or access error"
输出:
helloworld@LG-virtual-machine:~/code$ python test.py
Error: File not found or access error
Traceback (most recent call last):
File "test.py", line 3, in <module>
fh = open("a.txt",‘w‘)
IOError: [Errno 13] Permission denied: ‘a.txt‘
helloworld@LG-virtual-machine:~/code$ chmod +w a.txt
helloworld@LG-virtual-machine:~/code$ python test.py
Error: File not found or access error
try:
正常的操作
......................
except ExceptionType, Argument:
你可以在这输出 Argument 的值...
实例:
# -*- coding: UTF-8 -*-
def temp_convert(var):
try:
return int(var)
except ValueError,Arg:
print "参数不包含数字:",Arg
print temp_convert(‘xyz‘)
输出:
helloworld@LG-virtual-machine:~/code$ python test.py
参数不包含数字: invalid literal for int() with base 10: ‘xyz‘
None
触发异常:
raise [Exception [, args [, traceback]]]
语句中 Exception 是异常的类型(例如,NameError)参数标准异常中任一种,args 是自已提供的异常参数。
# -*- coding: UTF-8 -*-
def mye(level):
if level < 1:
raise Exception,"Invalid Error!" #触发异常后,后面的代码>将不会被执行
try:
mye(0)
except Exception,err:
print 1,err
else:
print 2
输出:
helloworld@LG-virtual-machine:~/code$ python test.py
1 Invalid Error!
# -*- coding: UTF-8 -*-
class NetworkError(RuntimeError):
def __init__(self, arg):
self.args = arg
try:
raise NetworkError("Bad hostName")
except NetworkError,e:
print e.args
输出:
helloworld@LG-virtual-machine:~/code$ python test.py
(‘B‘, ‘a‘, ‘d‘, ‘ ‘, ‘h‘, ‘o‘, ‘s‘, ‘t‘, ‘N‘, ‘a‘, ‘m‘, ‘e‘)
问题:为什么输出一个一个字母?以后再答
原文:https://www.cnblogs.com/qiulinzhang/p/9513576.html