about try and exception

Carl J. Van Arsdall cvanarsdall at mvista.com
Thu Nov 17 19:42:17 EST 2005


Shi Mu wrote:
> On 11/17/05, Carl J. Van Arsdall <cvanarsdall at mvista.com> wrote:
>   
>> 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.
>>
>>
>> -Carl
>>
>> 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
>>>       
> It is true. If I want to run the statement after the division error
> such as n=1/2, what should I do?
>   

move the n =1/2 after the division error.

Basically what will happen in an exception block is once an exception is 
thrown the interpreter will leave the block and handle the exception.  
Statements following the statement that caused the exception will then 
be ignored.

So if you want n=1/2 to be executed regardless of what happens during 
the line m = 2/0 move it outside the block

Ex:


try:
  m=2/0
except ZeroDivisionError:
  pass
n=1/2
print "Yes!!! This line will always print"
print n


or likewise you could experiment with:


try:
  n = 1/2
  m = 2/0
except:
  pass
print 'Yay'
print n


Here the line "n = 1/2" will get executed BEFORE the exception is thrown.

Hope that helps a bit.

-carl


-- 
--------------------------------------

Carl J. Van Arsdall
cvanarsdall at mvista.com
Build and Release
MontaVista Software




More information about the Python-list mailing list