Mizmor
Mizmor

Reputation: 1421

Can I cause an exception on purpose in python?

So this is a little bit of a strange question, but it could be fun!

I need to somehow reliably cause an exception in python. I would prefer it to be human triggered, but I am also willing to embed something in my code that will always cause an exception. (I have set up some exception handling and would like to test it)

I've been looking around and some ideas appear to be division by zero or something along those lines will always cause an exception--Is there a better way? The most ideal would be to simulate a loss of internet connection while the program is running....any ideas would be great!

Have fun!

Upvotes: 5

Views: 1512

Answers (3)

D_Bye
D_Bye

Reputation: 909

You can define your own Exceptions in Python, so you can create custom errors to suit your needs. You can test that certain conditions exist, and use the truthiness of that test to decide whether or not to raise your shiny, custom Exception:

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?

The documentation has some useful examples.

Upvotes: 4

Levon
Levon

Reputation: 143102

Yup, you can just plop

  1 / 0 

anywhere in your code for a run time error to occur, specifically in this case a ZeroDivisionError: integer division or modulo by zero.

This is the simplest 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 too .. depends on your specific needs.

Upvotes: 1

Makoto
Makoto

Reputation: 106470

Yes, there is: You can explicitly raise your own exceptions.

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

You would want to raise an appropriate exception/error for loss of network connectivity.

Upvotes: 5

Related Questions