Python Forum
best way to force an exception - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: best way to force an exception (/thread-30432.html)



best way to force an exception - Skaperen - Oct-20-2020

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?


RE: best way to force an exception - bowlofred - Oct-21-2020

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")



RE: best way to force an exception - Gribouillis - Oct-21-2020

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.