-1

I am logging any errors in my code, I have tried using:

try:
    #some deliberately dodgy code
Except Exception:
    print(Exception) #i am actually passing this to a function to add it in a file

but all I am getting is: <class 'Exception'>

2
  • except Exception as e: ; print(e) Commented Jul 6, 2020 at 19:44
  • Exception is a class. In the except clause, you should have Exception as e in order to print it. Commented Jul 6, 2020 at 19:51

3 Answers 3

1
try:
    #some deliberately dodgy code possibly involving pig's head (ask dodgy Dave)
except Exception as exc:
    print(exc)

exc is not a string (it's an exception object) but print will call its __str__ method which will return the message string with which it was instantiated

(you don't need to call it exc, you can call it anything you like, but exc or e are quite commonly used)

If you want the message in a variable you can always do explicitly

message = str(exc)  # now it really is a string

inside the except block

Sign up to request clarification or add additional context in comments.

Comments

0

Exception is a class, you should make an object inherited from Exception, like this:

try:
    #some deliberately dodgy code
Except Exception e:
    print(e)

Comments

0

You are actually on the right track, but your code should look instead as follows.

try:
    #some deliberately dodgy code
except Exception as message:
    print(message)

You can take a look at this post, Converting Exception to a string in Python 3, for more details and deeper understanding.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.