Python - 引发异常


您可以使用 raise 语句以多种方式引发异常。raise 语句的一般语法如下 -

句法

raise [Exception [, args [, traceback]]]

这里,Exception 是异常的类型(例如,NameError),argument 是异常参数的值。参数是可选的;如果未提供,则异常参数为 None。

最后一个参数traceback也是可选的(在实践中很少使用),如果存在,则是用于异常的traceback对象。

例子

异常可以是字符串、类或对象。Python 核心引发的大多数异常都是类,其参数是类的实例。定义新的异常非常简单,可以按如下方式完成 -

def functionName( level ): if level <1: raise Exception(level) # The code below to this would not be executed # if we raise the exception return level

注意- 为了捕获异常,“except”子句必须引用作为类对象或简单字符串抛出的相同异常。例如,要捕获上述异常,我们必须编写 except 子句,如下所示 -

try: Business Logic here... except Exception as e: Exception handling here using e.args... else: Rest of the code here...

以下示例说明了引发异常的用法 -

def functionName( level ): if level <1: raise Exception(level) # The code below to this would not be executed # if we raise the exception return level try: l=functionName(-10) print ("level=",l) except Exception as e: print ("error in level argument",e.args[0])

这将产生以下输出-

error in level argument -10