0

I've got a program that gets some python code from the user and executes it. The problem is that if an error occurs, an error is raised.

Is there a way to catch if an error occurred, and if it has, just print it instead of raise it?

I want to really know the whole message that's raised, if that's possible.

I'm using python 2.7.9 on osx Yosemite.

dccsillag
  • 919
  • 4
  • 14
  • 25

1 Answers1

1

It's as simple as

try:
    run_my_code()
except:
    print "Exception caught"

You can even print the exception details:

try:
    run_my_code()
except Exception as e:
    print "Exception message: " + e.message

For the most part, you will not want to catch all Exceptions - you should identify which exceptions are to be thrown and handle those individually. However if your intent is to prevent the program from exiting and/or print all exceptions, then catching all exceptions as fine.

Martin Konecny
  • 57,827
  • 19
  • 139
  • 159
  • But I was looking at the definitions of the classes of errors, and not all of them were defined as `class ErrorName(Exception):`. Does then exception include these ones? – dccsillag May 06 '15 at 17:37
  • Yes, because all the exceptions you want to catch are subclasses of Exception. It may not be a direct subclass, but a subclass of a subclass of Exception. – Martin Konecny May 06 '15 at 17:48