2024-10-01 13:35:26 发布
网友
正在尝试try/catch字符串格式函数中出现异常
try
catch
有人知道怎么做吗
"Hi {var1}! Here is {var2} Test!".format(var1= getMessage(), var2=getAnotherMessage())
有没有办法try/catch单个getMessage()和getAnotherMessage()函数中的异常
getMessage()
getAnotherMessage()
如果您使用的是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()))
现在,如果出现一些异常,在我们进入格式化部分之前,会为各个函数引发异常
如果您使用的是Python3.6或更高版本,请尝试以下内容
虽然这在我看来相当难看,而且只有在两个抛出异常的函数都需要对同一异常进行不同处理时才有意义。也许这更像是一个设计问题
您可以为单个函数添加try-except块,如下所示
现在,如果出现一些异常,在我们进入格式化部分之前,会为各个函数引发异常
相关问题 更多 >
编程相关推荐