Python Forum

Full Version: best way to force an exception
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
in a try part of a try/except i want a certain conditional test to run the except part. it seems the simple way to do that is to throw an exception the except part will catch. what is the best or most pythonic way to do that?
I would assume you'd just raise the exception that you want to catch.

debug = True
try:
    # run the exception
    if debug:
        raise ZeroDivisionError
except ZeroDivisionError:
    print("Got division error without actually dividing")

print("all done")
skaperen Wrote:what is the best or most pythonic way to do that?
There is no best way unless you show some real code. This question needs some context.