Welcome to the Treehouse Community
Looking to learn something new?
Daniel Petrov3,495 Points
can we have two try catches in one function and how we relate them?
not sure how to make this one working. tried different ways. when I test it and call the function in workspaces it returns "name 'arg' is not defined" even though I set it up as an input.
# EXAMPLES # squared(5) would return 25 # squared("2") would return 4 # squared("tim") would return "timtimtim" def squared(arg): try: arg = int(arg) except ValueError: return(arg * len(arg)) try: arg = str(arg) except ValueError: return(arg ** 2)
Ryan Ruscett23,307 Points
You can have a try that does several things, and you can attempt to catch multiple exceptions. But you done put two try excepts inside a single function.
If you have to do a try and except, it's most likely because you know of an opportunity for failure. This opportunity arises because you are performing an action. If you have two try and excepts in one function. It would mean you are trying two actions that could fail in the same function. This would be cause enough to break out the work into two functions.
When you try something, you could receive different exceptions. So you can do a try and except multiple exceptions. This is done by separating them with a comma or using multiple except statements.
Does this help at all?