一、
print int('0.5')
运行后程序得到错误提示提示
Traceback (most recent call last): File "C:\Users\29617\workspace\hh\test\com\java.py", line 1, in <module> print int('0.5') ValueError: invalid literal for int() with base 10: '0.5'
意思是,在java.py这个文件,你用了不是十进制能够表示的字符,没办法转为int值。
二、打开一个文件
f = file('non-exist.txt')
print 'File opened'
f.close()
若文件因某种原因没有出现在应该出现的·文件夹里,程序就会报错
IOError: [Errno 2] No such file or directory: 'non-exist.txt'
程序在出错处中断,后面的不会执行。在python中,可以使try....except语句来处理异常。
做法是,把可能引发异常的语句放在 try-块中,把处理异常的语句放在 except-块中。
1 try: 2 f = file('non-exist.txt') 3 print 'File opened!' 4 f.close() 5 except: 6 print 'File not exists.' 7 print 'Done'
当程序在try内部打开文件引发异常时,会跳过try中剩下的代码,直接跳转到except中的 语句处理异常。
所以输出了“File not exists.”
若文件顺利打开,则输出“ File opened ! ",而不会去执行except中的语句。
无论如何,程序不会中断,最后都会输出“Done”