about try and exception

Bruno Desthuilliers bdesth.quelquechose at free.quelquepart.fr
Sat Nov 19 11:37:56 CET 2005


Shi Mu a écrit :
> On 11/17/05, Carl J. Van Arsdall <cvanarsdall at mvista.com> wrote:
> 
(Carl's top-post corrrected. Carl, please do not top-post)
>>
>>
>>Ben Bush wrote:
>>
>>>I wrote the following code to test the use of "try...exception",
>>>and I want n to be printed out. However, the following code's output is:
>>>Traceback (most recent call last):
>>>  File
>>>"C:\Python23\lib\site-packages\Pythonwin\pywin\framework\scriptutils.py",
>>>line 310, in RunScript
>>>    exec codeObject in __main__.__dict__
>>>  File "C:\py\use\tryExVa.py", line 7, in ?
>>>    print n
>>>NameError: name 'n' is not defined
>>>
>>>the code is here:
>>>
>>>try:
>>>    m=2/0
>>>    n=1/2
>>>except ZeroDivisionError:
>>>    pass
>>>print "Yes!!! This line will always print"
>>>print n

 >>I would think that when the exception occurs the interpreter exits the
 >>block of code it is currently in and enters the exception block.
 >>
 >>Thus the line n = 1/2 would never get executed.
>
> It is true. 

Indeed...

> If I want to run the statement after the division error
> such as n=1/2, what should I do?

Depends on what you mean by "after". But I think this is what you want:

try:
   m = 2 / 0
except ZeroDivisionError:
   m = 0 # or whatever default value
n = 1/2





More information about the Python-list mailing list