I am trying to write a stand alone Class that can be imported. As part of this I’d like to throw exceptions in my Class that can be caught and dealt with in the Main. Is it possible to throw specific exceptions to Main for the user/developer to deal with?
I’m reasonable comfortable using the try: and except: in the Class and the Main to throw their own exceptions, it’s getting the Class to pass a specific exception onto the Main that I can’t work out.
Also, is it possible to some how set up the Python class so that it informs the user what exceptions they have to be able to catch to use my specific Class?
Thanks.
Check out the python tutorial section on user defined exceptions and also the section “Exceptions are Classes Too”. You can define your own exceptions as subclasses of the
Exceptionclass, and then catch them in your main.Here’s a quick example, although the one in the tutorial is better:
and then later in your main method:
Lastly, you typically inform the client of your module what exceptions might be raised in the documentation. The conventions for Python docstrings says:
Edit: You should also take a look at the python library reference on exceptions for the list of standard exception classes, which may be appropriate for you to subclass.