Can I raise an exception specifically for python?

So this is a bit of a strange question, but it might be interesting!

I need to somehow reliably throw an exception in python. I would prefer it to be caused by a person, but I also want to inject something into my code, which will always be the cause of the exception. (I have configured exception handling and would like to test it)

I look around, and some ideas seem to be dividing by zero, or something in this direction will always be the cause of the exception. Is there a better way? The most ideal would be to simulate the loss of an Internet connection while the program is running ... any ideas would be great!

Good luck

+5
source share
3 answers

Yes, there is: you can explicitly create your own exceptions.

raise Exception("A custom message as to why you raised this.")

/ .

+5

Python, . , , , , :

class MyFancyException(Exception): pass

def do_something():
    if sometestFunction() is True:
        raise MyFancyException
    carry_on_theres_nothing_to_see()    

try:
    do_something()
except MyFancyException:
    # This is entirely up to you! 
    # What needs to happen if the exception is caught?

.

+3

Yup, you can just flop

  1 / 0 

anywhere in your code for a runtime error, particularly in this case a ZeroDivisionError: integer division or modulo by zero.

This is the easiest way to get an exception by embedding something in your code (as you mentioned in your post). You can, of course, raise your own Exceptions ... depends on your specific needs.

0
source

All Articles