简体   繁体   中英

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

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM