Search code examples
pythonexceptionraise

raise custom exception in python


I could not get what is wrong with the code ? when I execute nothing happens. I am expecting my custom error message.

def testing():
  try:
    raise Exception('My error!')
  except:
    pass

testing()

Solution

  • You are successfully raising an error. And the try/catch statements sees it, and goes to catch as you have raised an error.

    To fully customize errors you can declare them as so:

    class CustomError(Exception):
        pass
    raise CustomError("An error occurred")
    

    results in

    __main__.CustomError: An error occurred