about try and exception

Shi Mu samrobertsmith at gmail.com
Thu Nov 17 19:55:54 EST 2005


On 11/17/05, Carl J. Van Arsdall <cvanarsdall at mvista.com> wrote:
> 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
If we do not know when the error will happen during the calculation
but still want to continue till end, what should I do?
for example:

def test(a,b,c):
    return a/(b-c)
q=[1,1,2,2,4,6,9,0]
for i in range(len(q)):
    print test(q[i],q[i+1],q[i+2])

the output is:
-1
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:\tt\try2005.py", line 19, in ?
    print test(q[i],q[i+1],q[i+2])
  File "C:\tt\try2005.py", line 16, in test
    return a/(b-c)
ZeroDivisionError: integer division or modulo by zero



More information about the Python-list mailing list