2

Trying to try / catch an exception in string format function.

Anyone has an idea how to do this?

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

Is there a way to try / catch an exception in the individual getMessage() and getAnotherMessage() functions?

1
  • 1
    Store them in a local variable before doing the .format(). Commented Dec 15, 2020 at 8:44

2 Answers 2

1

If you're using python 3.6 or higher, try something like this.

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!"

Though this seems rather ugly to me and it only makes sense if you need different handling of the SAME exception for each of the two functions throwing them. Maybe that's more of a design issue then.

Sign up to request clarification or add additional context in comments.

Comments

1

You can add the try-except block for the individual function as the following

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()))

Now if some exception occurs, it gets raised for the individual functions before we come into the formatting part.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.