[PYTHON] Intentionally throw an exception with raise

import sys, traceback

number1 = 100
number2 = 1

print('start')
try:
    print(1)
    raise NameError('I intentionally caused a name error.')
    print(2)
except NameError as e:
    print('You called an undefined variable.')
    sys.stderr.write(traceback.format_exc())
finally:
    print('end')

Execution result


start
1
You called an undefined variable.
end

After the raise NameError in the try block Note that print (2) will not be executed.

Run-time error


Traceback (most recent call last):
  File "Main.py", line 9, in <module>
    raise NameError('I intentionally caused a name error.')
NameError:I intentionally caused a name error.

Recommended Posts

Intentionally throw an exception with raise
Fizzbuzz with exception handling
`==` may throw an exception between objects that are circularly referenced
Create an environment with virtualenv
Create an API with Django
Try an autoencoder with Pytorch
Creating an egg with python