如何尝试捕获字符串格式的异常?

2024-10-01 13:35:26 发布

您现在位置:Python中文网/ 问答频道 /正文

正在尝试try/catch字符串格式函数中出现异常

有人知道怎么做吗

"Hi {var1}! Here is {var2} Test!".format(var1= getMessage(), var2=getAnotherMessage())

有没有办法try/catch单个getMessage()getAnotherMessage()函数中的异常


Tags: 函数字符串testformathereis格式hi
2条回答

如果您使用的是Python3.6或更高版本,请尝试以下内容

try:
    var1= getMessage()
except Exception:
    # do something
    pass
try:
    var2=getAnotherMessage()
except Exception:
    # do something else
    pass
result = f"Hi {var1}! Here is {var2} Test!"

虽然这在我看来相当难看,而且只有在两个抛出异常的函数都需要对同一异常进行不同处理时才有意义。也许这更像是一个设计问题

您可以为单个函数添加try-except块,如下所示

def getMessage():
    try:
        return "Nithin"
    except:
        raise Exception("Error in getMessage function")

def getAnotherMessage():
    try:
        return "Physics"
    except:
        raise Exception("Error in getAnotherMessage function")

print("Hi {}! Here is {} Test!".format(getMessage(), getAnotherMessage()))

现在,如果出现一些异常,在我们进入格式化部分之前,会为各个函数引发异常

相关问题 更多 >