Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to catch an exception message in python? [duplicate]

I want something of the form

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

i.e 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")
like image 354
Eeshaan Avatar asked Jun 10 '26 01:06

Eeshaan


2 Answers

Try this:

except Exception as e:
    print(str(e))
like image 192
Jakob Avatar answered Jun 11 '26 15:06

Jakob


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))
like image 25
Óscar López Avatar answered Jun 11 '26 14:06

Óscar López



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!