返回函数中填充的异常

时间:2020-04-08 09:16:23

标签: python exception

我的代码是这样的:

try:
    function()
except:
    #Error

功能代码:

def function():
    try:
        #something
    except:
        #function error

是否有可能以某种方式返回从函数返回的错误?如果没有,则返回#error。

类似这样的东西

    try:
        function()
    except:
        if #function error:
            #function error
        #error

1 个答案:

答案 0 :(得分:1)

是的,您可以使用以下语法进行操作:

def function():
    try:
        #something
    except Exception as e:
        return e

在调用函数的外部代码中,不需要try, except,因为函数正在返回一个Exception而不是 raise < / em>。您可以改为检查函数的返回值是否为Exception的实例,如下所示:

result = function()
if isinstance(result, Exception):
    #handle error
else:
    #do whatever you want with result

或者,您可以让函数在发生错误时引发错误,然后在调用代码中进行处理,而不是像下面这样返回错误:

def function():
    #do whatever error-prone code

try:
    result = function()
    #do whatever you want with result
except Exception as e:
    #handle error