difference between and before the function & in the function

When I use try before the function, it raise error. but if I use it in the function it will be fine. why?(what is the order of evaluation of these codes? ). Any help is appreciated.

try:
    def chiz(dict, key):
        return dict[key]
except:
    print("somethig went wrong")
user_01 = {
    "name": "armin",
    "age": 20.51
}
chiz(user_01, "weight")

>>>Traceback (most recent call last):
  File "C:UsersuserPycharmProjectspythonWhiletest.py", line 11, in <module>
    chiz(user_01, "weight")
  File "C:UsersuserPycharmProjectspythonWhiletest.py", line 3, in chiz
    return dict[key]
KeyError: 'weight'


def chiz(dict, key):
    try:
        return dict[key]

    except :
        print("somethig went wrong")

user_01 = {
    "name": "armin",
    "age": 20.51
}

chiz(user_01, "weight")

Answer

The try in your first example is not evaluated when the function is being called, only when the function is first being defined, at which point there are no exceptions being raised.

It’s not until you actually call the function with arguments where the key doesn’t exist in the given dictionary that an exception is actually raised and that try/except clause isn’t being evaluated then.

Your second example is the correct way to do what you’re trying to do:

In [4]: def chiz(dict, key): 
   ...:     try: 
   ...:         return dict[key] 
   ...:     except: 
   ...:         print("Something went wrong") 
   ...:                                                                         

In [5]: chiz(user_01, "weight")                                                 
Something went wrong

That being said, reconsider that bare except clause. It is equivalent to saying except BaseException: which is probably not what you want and is against PEP8 recommendations. In this case, you should probably be using except KeyError: or, at the most broad, except Exception:.

When catching exceptions, mention specific exceptions whenever possible instead of using a bare except: clause. A bare except: clause will catch SystemExit and KeyboardInterrupt exceptions, making it harder to interrupt a program with Control-C, and can disguise other problems. If you want to catch all exceptions that signal program errors, use except Exception: (bare except is equivalent to except BaseException:). A good rule of thumb is to limit use of bare ‘except’ clauses to two cases:

  • If the exception handler will be printing out or logging the traceback; at least the user will be aware that an error has occurred.
  • If the code needs to do some cleanup work, but then lets the exception propagate upwards with raise. try…finally can be a better way to handle this case.

And from PEP463:

any situation where you catch an exception you don’t expect to catch is an unnecessary bug magnet.