Python Practice Creating and Using Functions in Python Practice Functions Thank You!

How to find the "max allowed is 42" text from the MessageToLongError?

I couldn't fine the text "max allowed is 42" from the 2nd error so I just copied pasted it to my except statement.

4 Answers

Steven Parker
Steven Parker
177,538 Points

That's cheating! :stuck_out_tongue_closed_eyes: It's funny that it let you get away with that. :smirk:

But the way to capture the built-in text is with the "as" operator:

except MessageTooLongError as err:   # this copies the exception text into "err"
    print(f"Oh no! Your message was too long ({err})")

Yes. That's cheating :)), the right code is:

except MessageTooLongError as err:
print("Oh no! Your message was too long ({})".format(err))

Steven Parker
Steven Parker
177,538 Points

That will work also. I used an f-string instead of "format" in my example as it makes the code a bit more compact, and to my eyes a bit easier to read. And to cover all the options, one other method that would produce the same results is a formatted string:

    print("Oh no! Your message was too long %s" % err)

That great Steven! How can i know more option like f-string and % err, can you share something. Sorry because i just start learning coding

Steven Parker
Steven Parker
177,538 Points

Learning the other "tools in the toolbox" will be a natural part of your progress as you continue learning. The earlier courses concentrate on showing you at least one way to do things, which will typically be the "classic" methods like "format".

For a definitive reference I use the online Python manual, but it's pretty dry reading. I'd recommend just sticking with the courses for now and if your curiosity is overwhelming, check out some of the conference videos.

Thanks for your advice Steven.