English 中文(简体)
其他目的和最后处理例外情况
原标题:Purpose of else and finally in exception handling
  • 时间:2011-05-18 22:53:23
  •  标签:
  • python

<代码>le 和.finally关于例外处理章节是否多余? 例如,以下两部法典是否有什么区别?

try:
    foo = open("foo.txt")
except IOError:
    print("error")
else:
    print(foo.read())
finally:
    print("finished")

and

try:
    foo = open("foo.txt")
    print(foo.read())
except IOError:
    print("error")
print("finished")

More generally, can t the contents of else always be moved into the try, and can t the contents of finally just be moved outside the try/catch block? If so, what is the purpose of else and finally? Is it just to enhance readability?

问题回答

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.

如果您将<代码>*>le栏内所载内容移至>>>>,则您还将列出在<代码>中可能出现的例外情况。 如果是,

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.

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.

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!")

始终如一地实施

如果没有例外。

我倾向于将该守则列入<代码>中,即最终栏,在<代码>try/code>后执行,但区块除外。

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()

There are 3 possible "states": never occurred, handled and unhandled. You can map the control flow of the try-catch-else-finally clause into these 3 states like that:

from traceback import print_last

e_state =  unhandled exception 
try:
    # cause an exception here [or don t]
except SomeException as e: # use a suitable [or not] exception type here
    e_state =  handled exception 
    print( in "except" )
else:
    e_state =  no exception 
    print( in "else" )
finally:
    print(f in "finally". {e_state} occurred )
    if e_state ==  handled exception :
        print_last() # since the exception was caught - explicitly inform about it

Full examples below:

1. Handled Exception

from traceback import print_last

e_state =  unhandled exception 
try:
    1 / 0
except ZeroDivisionError as e:
    e_state =  handled exception 
    print( in "except" )
else:
    e_state =  no exception 
    print( in "else" )
finally:
    print(f in "finally". {e_state} occurred )
    if e_state ==  handled exception :
        print_last()

产出:

in "except"
in "finally". handled exception occurred

Traceback (most recent call last):
  File "...IPython/core/interactiveshell.py", line 3251, in run_code
    exec(code_obj, self.user_global_ns, self.user_ns)
  File ".../T/ipykernel_59815/1316012763.py", line 5, in <module>
    1 / 0
ZeroDivisionError: division by zero

2. Unhandled Exception

from traceback import print_last

e_state =  unhandled exception 
try:
    1 / 0
except KeyError as e:
    e_state =  handled exception 
    print( in "except" )
else:
    e_state =  no exception 
    print( in "else" )
finally:
    print(f in "finally". {e_state} occurred )
    if e_state ==  handled exception :
        print_last()

产出:

in "finally". unhandled exception occurred

---------------------------------------------------------------------------
ZeroDivisionError                         Traceback (most recent call last)
Input In [14], in <module>
      3 e_state =  unhandled exception 
      4 try:
----> 5     1 / 0
      6 except KeyError as e:
      7     e_state =  handled exception 

ZeroDivisionError: division by zero

3. No Exception

from traceback import print_last

e_state =  unhandled exception 
try:
    1 / 2
except ZeroDivisionError as e:
    e_state =  handled exception 
    print( in "except" )
else:
    e_state =  no exception 
    print( in "else" )
finally:
    print(f in "finally". {e_state} occurred )
    if e_state ==  handled exception :
        print_last()

产出:

in "else"
in "finally". no exception occurred




相关问题
Can Django models use MySQL functions?

Is there a way to force Django models to pass a field to a MySQL function every time the model data is read or loaded? To clarify what I mean in SQL, I want the Django model to produce something like ...

An enterprise scheduler for python (like quartz)

I am looking for an enterprise tasks scheduler for python, like quartz is for Java. Requirements: Persistent: if the process restarts or the machine restarts, then all the jobs must stay there and ...

How to remove unique, then duplicate dictionaries in a list?

Given the following list that contains some duplicate and some unique dictionaries, what is the best method to remove unique dictionaries first, then reduce the duplicate dictionaries to single ...

What is suggested seed value to use with random.seed()?

Simple enough question: I m using python random module to generate random integers. I want to know what is the suggested value to use with the random.seed() function? Currently I am letting this ...

How can I make the PyDev editor selectively ignore errors?

I m using PyDev under Eclipse to write some Jython code. I ve got numerous instances where I need to do something like this: import com.work.project.component.client.Interface.ISubInterface as ...

How do I profile `paster serve` s startup time?

Python s paster serve app.ini is taking longer than I would like to be ready for the first request. I know how to profile requests with middleware, but how do I profile the initialization time? I ...

Pragmatically adding give-aways/freebies to an online store

Our business currently has an online store and recently we ve been offering free specials to our customers. Right now, we simply display the special and give the buyer a notice stating we will add the ...

Converting Dictionary to List? [duplicate]

I m trying to convert a Python dictionary into a Python list, in order to perform some calculations. #My dictionary dict = {} dict[ Capital ]="London" dict[ Food ]="Fish&Chips" dict[ 2012 ]="...

热门标签