发布时间:2019-07-31 09:30:45编辑:auto阅读(1532)
最常见的异常就是文件打开 时,找不到文件
try: f = open(“file.txt”,”r”) except IOError, e: print e
然后就是命名空间异常,也就是没有定义这个变量或对象
try: s = None if s is None: print "s 是空对象" raise NameError #如果引发NameError异常,后面的代码将不能执行 print len(s) except TypeError: print "空对象没有长度"
还有就是违反运算法则的错误,两个例子
def divide(a, b):
try:
return a / b
except ZeroDivisionError as e:
raise ValueError('Invalid inputs') from e
x , y = 7, 3
try:
result = divide(x, y)
except ValueError:
print('Invalid inputs')
else:
print('Result is %.1f' % result)try: s = "hello" try: print s[0] + s[1] print s[0] - s[1] except TypeError: print "字符串不支持减法运算" except: print "异常"
文件的读写,可以用异常处理方式做的更完善
try:
f = open("hello.txt", "r")
try:
print f.read(5)
except:
print "读文件异常"
finally:
print "释放资源"
f.close()
except IOError:
print "文件不存在"python中的常用异常如下:
AssertionError
AttributeError
IOError
ImportError
IndentationError
IndexError
KeyError
KeyboardInterrupt
NameError
SyntaxError
TypeError
UnboundLocalError
ValueError
参考
http://www.cnblogs.com/fnng/p/3518202.html
上一篇: python环境配置
下一篇: 安装 python2.7.10
51300
50749
41345
38158
32629
29526
28375
23249
23216
21538
1613°
2347°
1950°
1889°
2224°
1934°
2620°
4398°
4241°
3012°