Is there a way to accomplish the following in python?

try{
// something
} catch (e) {
// display e.message, e.name, e.linenumber
}

Recommended Answers

All 8 Replies

try:
   value=int('surely not number')
except ValueError as e:
   print e

I want to except all error, not just 1 type

Would that be done with except Exception?

It considered not good practice to catch all errors but then you can do:

import sys
try:
    value=int('surely not number')
except:
    etype,emsg,tb = sys.exc_info()
    print "Unexpected error:", emsg
##    raise ## recommended to raise unspecific error to forward it

Exception documentation is excellent, I recommend to read it. Actually I realized new thing from there now as looked info for you: after possible exception point it is better to put rest of statements in else part not inside the try.

why wouldn't it be good practise?

My scenerio is that i want the program to continue even though there's an error, but log it a log file/ print it to screen. Basically i want to print the trackback msg without terminating the program

Document I linked to says:

The last except clause may omit the exception name(s), to serve as a wildcard. Use this with extreme caution, since it is easy to mask a real programming error in this way! It can also be used to print an error message and then re-raise the exception (allowing a caller to handle the exception as well):

Always specify the exceptions to catch.
Never use bare except clauses.
Bare except clauses will catch unexpected exceptions, making your code exceedingly difficult to debug.

Let you code run if you catch new exception,you can put them in except(all my catch)

try:
    x = float(raw_input('Enter the first number: '))
    y = float(raw_input('Enter the second number: '))
    print x / y
except (ZeroDivisionError, TypeError, ValueError):
    print 'Your numbers were bogus...'

Or you can split it upp.

try:
    x = float(raw_input('Enter the first number: '))
    y = float(raw_input('Enter the second number: '))
    print x / y
except ZeroDivisionError:
    print "The second number can't be zero!"
except ValueError:
    print "That wasn't a number, was it?"

I know about re-raising, but then it would still terminate the program.

I know about re-raising, but then it would still terminate the program.

If your program encounters an unexpected exception, the best thing to do is usually to terminate the program, because your program's data were modified in an unpredictable way.

It is not a universal rule however. For example, if your program is an editor, you may want to save the current files somewhere before crashing with traceback. In such cases, a bare except: with re-raise could be the best solution.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.