Why can't I throw an exception after I throw it?

Why can't I instantiate Exception after I catch this Exception class? Oddly enough, I encountered this error when I run a script from a function, but not when run directly in the python shell.

In [2]: def do():
   ...:     try:
   ...:         raise ValueError('yofoo')
   ...:     except TypeError, ValueError:
   ...:         raise ValueError('yo')
   ...: 

In [3]: do()
---------------------------------------------------------------------------
UnboundLocalError                         Traceback (most recent call last)
<ipython-input-3-30c46b84d9a4> in <module>()
----> 1 do()

<ipython-input-2-b62158d6343b> in do()
      1 def do():
      2     try:
----> 3         raise ValueError('yofoo')
      4     except TypeError, ValueError:
      5         raise ValueError('yo')

UnboundLocalError: local variable 'ValueError' referenced before assignment

Expected error here:

In [3]: try:
   ...:     raise ValueError("foo")
   ...: except ValueError:
   ...:     raise ValueError("bar")
   ...: 
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-3-d5c83419a5ea> in <module>()
      2     raise ValueError("foo")
      3 except ValueError:
----> 4     raise ValueError("bar")
      5 

ValueError: bar
+4
source share
1 answer
except TypeError, ValueError:

it should be

except (TypeError, ValueError):

When you use except TypeError, ValueError:, you assign an instance of Exception to the variable name ValueError.

, Python do, , ValueError , except TypeError, ValueError: ValueError. try-suite, raise ValueError('yofoo'), ValueError . , UnboundLocalError.


:

... except (RuntimeError, TypeError, NameError):
...     pass

, , ValueError, e: , , ValueError e: Python ( ). - . RuntimeError, TypeError (RuntimeError, TypeError): RuntimeError TypeError: , .

+8

Source: https://habr.com/ru/post/1531222/


All Articles