像其他语言一样,python通过try-except提供了运行时错误异常处理方法。 一些最常见的标准异常包括IndexError,ImportError,IOError,ZeroDivisionError,TypeError。
Exception是python中所有异常的基类。您可以在此处检查异常层次结构(https://docs.python.org/2/library/exceptions.html#exception-hierarchy)。
让我们尝试访问索引超出范围的数组元素并处理相应的异常。
# Python program to handle simple runtime error a = [1, 2, 3] try: print "Second element = %d" %(a[1]) # Throws error since there are only 3 elements in array print "Fourth element = %d" %(a[3]) except IndexError: print "An error occurred"
输出:
Second element = 2An error occurred
一个try语句可以具有一个以上的except子句,以指定不同异常的处理程序。请注意,最多将执行一个处理程序。
# Program to handle multiple errors with one except statement try : a = 3 if a < 4 : # throws ZeroDivisionError for a = 3 b = a/(a-3) # throws NameError if a >= 4 print "Value of b = ", b # note that braces () are necessary here for multiple exceptions except(ZeroDivisionError, NameError): print "Error Occurred and Handled"
输出:
Error Occurred and Handled
如果您将“a”的值更改为大于或等于4,则输出为
Value of b = Error Occurred and Handled
上面的输出是因为python一旦尝试访问b的值,就会发生NameError。
Else子句:
在python中,您还可以在try-except块上使用else子句,该子句必须出现在所有except子句之后。仅当try子句未引发异常时,代码才进入else块。
# Program to depict else clause with try-except # Function which returns a/b def AbyB(a , b): try: c = ((a+b) / (a-b)) except ZeroDivisionError: print "a/b result in 0" else: print c # Driver program to test above function AbyB(2.0, 3.0) AbyB(3.0, 3.0)
上面程序的输出将是:
-5.0a/b result in 0
引发异常:
raise语句使程序员可以强制发生特定的异常。raise中唯一的参数表示要引发的异常。这必须是异常实例或异常类(从Exception派生的类)。
# Program to depict Raising Exception try: raise NameError("Hi there") # Raise Error except NameError: print "An exception" raise # To determine whether the exception was raised or not
上面代码的输出将简单地打印为“An exception”,但是由于最后一行中的raise语句,最后也会发生运行时错误。因此,命令行上的输出将如下所示
Traceback (most recent call last): File "003dff3d748c75816b7f849be98b91b8.py", line 4, in raise NameError("Hi there") # Raise ErrorNameError: Hi there