简体   繁体   中英

How to catch an exception message in python?

I want something of the form

try:
  # code
except *, error_message:
  print(error_message)

ie I want to have a generic except block that catches all types of exceptions and prints an error message. Eg. "ZeroDivisionError: division by zero". Is it possible in python?

If I do the following I can catch all exceptions, but I won't get the error message.

try:
  # code
except:
  print("Exception occurred")

Try this:

except Exception as e:
    print(str(e))

This will allow you to retrieve the message of any exception derived from the Exception base class:

try:
    raise Exception('An error has occurred.')
except Exception as ex:
    print(str(ex))

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