Python中错误处理分为两类:语法错误和异常处理。
语法错误:
语法错误一般是指由于python语句、表达式、函数等存在书写格式活语法规则上的错误抛出的异常,如python常见的缩进控制,若同层次的执行语句存在缩进不同,会报语法错误(SyntaxError),一般在ide中会有明显的提示,其属于编译阶段的错误,一般是导致解析错误抛出错误;
>>>while True print 'Hello world'
SyntaxError: invalid syntax
异常处理:
异常处理一般是指python语法格式正确,但在运行过程出现错误,错误类型交由python中的内建异常进行说明,回朔处理,这种类型的处理一般都是出现在运行阶段,是需要处理的。
In [1]: 1/0
ZeroDivisionError: integer division or modulo by zero
In [2]: vin *3
NameError: name 'vin' is not defined
In [3]: '1'+1
TypeError: cannot concatenate 'str' and 'int' objects
1.捕捉异常
可以使用try/except语句。
try/except语句用来检测try语句块中的错误,从而让except语句捕获异常信息并处理。
当用户输入异常时,except可以保证程序可以正常执行。
In [4]: while True:
...: try:
...: x = int (raw_input("please input a number: "))
...: break
...: except ValueError:
...: print "Try again please.. The number is unvalid"
...:
please input a number: as
Try again please.. The number is unvalid
please input a number: 12
一个try声明可以对应多个except子句,一个except字句可以用元组的形式包含多个异常类型。
... except (RuntimeError, TypeError, NameError):
... pass
捕获未知错误:
在开发的时候,要判断所有可能出现的错误,是有一定难度的
如果希望程序无论出现任何错误,都不会因python解释器抛出异常而终止,可以再增加一个except
... expect:
... pass
- 另外,使用finally处理无论是否发生异常捕获都执行的代码,可以直接通过和try单独使用,也可以和except联合使用(此种情况放在except,else后面)
try :
n = int(raw_input("Input a number:"))
result = 21 / n
print result
except Exception as result: ##捕获未知异常;result:任意一个变量名
print "ERROR %s" % result
else: ##无异常时才会执行的代码
print "SUCCESS!"
finally: ##无论代码是否异常,均会输出。
print 'nNmM' *34
Input a number:sa
ERROR invalid literal for int() with base 10: 'sa'
Input a number:0
ERROR integer division or modulo by zero
2.抛出异常
异常抛出可以让我们定义主动抛出异常的逻辑,以提醒使用者需要进行某些必要的异常判断或者处理,python中的异常抛出使用关键字raise实现。
try:
f = open('a.txt')
s = f.readline()
i = int(s.strip())
except IOError as e:
print "I/O error({0}): {1}".format(e.errno, e.strerror)
except ValueError:
print "Could not convert data to an integer."
except:
print "Unexpected error:", sys.exc_info()[0]
raise ##抛出处理错误信息文件
##还可以将异常实例化,并且自定义添加一些属性
try:
raise Exception('spam', 'eggs')
except Exception as inst:
print type(inst) # the exception instance
print inst.args # arguments stored in .args
print inst # __str__ allows args to be printed directly
x, y = inst.args
print 'x =', x
print 'y =', y
<type 'exceptions.Exception'>
('spam', 'eggs')
('spam', 'eggs')
x = spam
y = eggs
3.异常传递性
异常的传递–当函数/方法执行出现异常,会将异常传递给函数/方法调用的一方。如果传递到主程序,依旧没有异常处理,程序才会终止,可以在主程序中增加异常捕获,而在主函数中调用其他函数,只要出现异常,都会传递到主函数的异常捕获中,这就不需要在代码中,增加大量的异常捕获,能够保证代码的整洁。
def demo():
return int(raw_input("Input number:"))
def demo2():
return demo()
try:
print demo()
except Exception as result:
print "Error: %s " % result
>>>Input number:12a
Error: invalid literal for int() with base 10: '12a'
4.自定义异常
def paswswd(): ##密码输入位数不小于8,否则输出异常
pwd = raw_input("PASSWD:")
if len(pwd) >=8:
return pwd
ex = Exception('Passwd is too short!!') ### 创建异常对象(可以添加错误信息)
raise ex
# 注意:只抛出异常而不捕获异常,代码会错出
try:
print paswswd()
except Exception as result:
print result
# 先创建异常对象,再抛出异常,再在主函数中捕获异常
>>>PASSWD:111
Passwd is too short!!
断言
可以理解为提前预言,让人更好的知道错误原因
def func(num,div):
assert (div != 0),'div不能为0' ##在执行程序内部,用assert对可能发生的错误进行预判。
return num / div
print func(10,0)
>>>AssertionError: div不能为0
参考资料: