search

Home  >  Q&A  >  body text

python - 为什么这段代码没有异常抛出?

In [8]: def bar():
   ...:     a = 10
   ...:     try:
   ...:         raise
   ...:     except:
   ...:         try:
   ...:             raise
   ...:         except:
   ...:             raise
   ...:     finally:
   ...:         return a


In [9]: bar()
Out[9]: 10
天蓬老师天蓬老师2787 days ago509

reply all(2)I'll reply

  • 天蓬老师

    天蓬老师2017-04-18 10:30:05

    This is quite interesting, let’s run a few codes first

    1. This code means that you don’t have to worry about how many layers of try you have. In fact, you just need to figure out why exceptions are not thrown under except
    def bar():
        a = 10
        try:
            print 1
            raise
        except:
            print 2
            raise
        finally:
            print 3
            return a
    
    bar()
    # 打印(没有抛出异常): 
    # 2
    # 3
    2. This code means that if finally has a return statement, no exception will be thrown, and if there is no return, an exception will be thrown
    def bar():
        a = 10
        try:
            print 1
            raise
        except:
            print 2
            raise
        finally:
            print 3
            # return a
    bar()
    # 打印(抛出了异常):
    # 2
    # Traceback (most recent call last):
    # 3
    #   File "/Users/xuxin/workplace/DailyScript/segmentfault/file_list_to_dict.py", line 23, in <module>
    #     bar()
    #   File "/Users/xuxin/workplace/DailyScript/segmentfault/file_list_to_dict.py", line 18, in bar
    #     raise ValueError()
    # ValueError
    3. I checked it out and saw this article on in-depth understanding of Python’s finally

    It seems that after f() throws an exception, it executes the return in except, but it does not return to the caller, but "persists" in executing the code in finally. At this point, I finally understand the true meaning of finally, which is that even if the return has been made, the code in finally must still be executed.

    We can also understand here that if there is a statement that requires an exit method in try, it will try to execute finally. If finally has a return method, it will return immediately and the previous exit statement will not be executed.
    At this time, we can take a look at this string of code

    def bar():
        a = 10
        try:
            print 1
            raise
        finally:
            print 3
            return a
    
    bar()
    # 打印(没有抛出异常): 
    # 3
    4. At this time, are you more clear about finally~

    Learn now and sell now. If there are any errors, please point out and correct them~

    reply
    0
  • ringa_lee

    ringa_lee2017-04-18 10:30:05

    If an exception is thrown in the end, isn’t your except statement in vain?

    reply
    0
  • Cancelreply