raise custom exception in python

11.7k views Asked by At

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()
2

There are 2 answers

1
Goldwave On BEST ANSWER

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
0
F.NiX On

You are raising an exception successfully. But you are catching that with try/except block. So nothing happens unless you describe it in except block.