Purpose of else and finally in exception handling

后端 未结 5 1654
耶瑟儿~
耶瑟儿~ 2020-12-12 23:35

Are the else and finally sections of exception handling redundant? For example, is there any difference between the following two code snippets?

相关标签:
5条回答
  • 2020-12-13 00:02

    finally block always executed

    Else block executed If there is not any exception.

    I prefer to put the code in finally block which is always executed after try and except blocks.

    I prefer to put the code in else block which is executed if the try clause does not raise an exception same like this

    Finally

    try:
      f = open("file.txt")
      f.write("change file")
    except:
      print("wrong")
    finally:
      f.close()
    

    Else

    try:
       f = open("file.txt")
       f.write("change file")
    except:
      print("wrong")
    else:
      print("log => there is not any exception")
    finally:
        f.close()
    
    0 讨论(0)
  • 2020-12-13 00:06

    If you move the contents of the else block inside the try block, you will also catch exceptions that might happen during the else block. If the line

    print(foo.read())
    

    in your example throws an IOError, your first code snippet won't catch that error, while your second snippet will. You try to keep try blocks as small as possible generally to really only catch the exceptions you want to catch.

    The finally block gets always executed, no matter what. If for example the try block contains a return statement, a finally block will still be executed, while any code beneath the whole try/except block won't.

    0 讨论(0)
  • 2020-12-13 00:07

    No matter what happens, the block in the finally always gets executed. Even if an exception wasn't handled or the exception handlers themselves generate new exceptions.

    0 讨论(0)
  • 2020-12-13 00:09
    try:
       print("I may raise an exception!")
    except:
       print("I will be called only if exception occur!")
    else:
       print("I will be called only if exception didn't occur!")
    finally:
       print("I will be called always!")
    
    0 讨论(0)
  • 2020-12-13 00:15

    finally is executed regardless of whether the statements in the try block fail or succeed. else is executed only if the statements in the try block don't raise an exception.

    0 讨论(0)
提交回复
热议问题