Python Catching Any Error
Contents |
here for a quick overview of the site Help Center Detailed answers to any questions you might have Meta Discuss the workings and policies of this site About Us Learn more about Stack Overflow the company Business Learn
Python Exception Message
more about hiring developers or posting ads with us Stack Overflow Questions Jobs Documentation Tags Users python print exception Badges Ask Question x Dismiss Join the Stack Overflow Community Stack Overflow is a community of 6.2 million programmers, just like you, helping
Python Exception Stack Trace
each other. Join them; it only takes a minute: Sign up Python: about catching ANY exception up vote 240 down vote favorite 37 How can I write a try/except block that catches all exceptions? python share|improve this question syntax for generic except clause in python edited Jul 10 '15 at 15:56 Mark Amery 24.2k12119151 asked Feb 14 '11 at 9:46 user469652 8,9372985137 1 Since I didn't see it linked here: docs.python.org/howto/doanddont.html#except. –delnan Feb 14 '11 at 16:32 3 Because I really don't know what exception to catch, and also the code is in a high level wrapper. –user469652 Feb 14 '11 at 20:45 1 In most cases you are, probably, doing smth wrong if you are trying to python custom exception catch any exception. I mean you can simply misspell something in your code and you will even don't know about it. It is a good practice to catch specific exceptions. –vwvolodya Sep 4 '14 at 12:25 To be more precise, catching all possible exceptions is only a problem if they are caught silently. It's hard to think of where else this approach is appropriate, other than where the caught error messages are printed to sys.stderr and possibly logged. That is a perfectly valid and common exception. –Evgeni Sergeev May 7 at 4:28 add a comment| 6 Answers 6 active oldest votes up vote 185 down vote accepted You can but you shouldn't: try: do_something() except: print "Caught it!" However, this will also catch exceptions like KeyboardInterrupt and you usually don't want that, do you? Unless you re-raise the exception right away - see the following example from the docs: try: f = open('myfile.txt') s = f.readline() i = int(s.strip()) except IOError as (errno, strerror): print "I/O error({0}): {1}".format(errno, strerror) except ValueError: print "Could not convert data to an integer." except: print "Unexpected error:", sys.exc_info()[0] raise share|improve this answer edited Feb 3 '13 at 20:58 answered Feb 14 '11 at 9:49 Tim Pietzcker 197k27263354 11 Possible workaround: effbot.org/zone/stupid-exceptions-keyboardinterrupt.htm –Mikel Feb 14 '11 at 9:52 5 Your last statement is not true, you need to explic
you have probably seen some. There are (at least) two distinguishable kinds of errors: syntax errors and exceptions. 8.1. Syntax Errors¶ Syntax errors, also known as parsing errors, are perhaps the most common kind of complaint
Python Try Without Except
you get while you are still learning Python: >>> while True print 'Hello world' python try except else File "
Python Catch Multiple Exceptions
little ‘arrow' pointing at the earliest point in the line where the error was detected. The error is caused by (or at least detected at) the token preceding the arrow: in the example, the error is detected http://stackoverflow.com/questions/4990718/python-about-catching-any-exception at the keyword print, since a colon (':') is missing before it. File name and line number are printed so you know where to look in case the input came from a script. 8.2. Exceptions¶ Even if a statement or expression is syntactically correct, it may cause an error when an attempt is made to execute it. Errors detected during execution are called exceptions and are not unconditionally fatal: you will https://docs.python.org/2.7/tutorial/errors.html soon learn how to handle them in Python programs. Most exceptions are not handled by programs, however, and result in error messages as shown here: >>> 10 * (1/0) Traceback (most recent call last): File "
to using except: without specifying any exception class at all, meaning that it will catch all exceptions. Generally it's better to only catch the exceptions you are expecting, e.g., KeyError or (IOError, OSError). I don't http://www.ianbicking.org/good-catch-all-exceptions.html disagree with him, but there are a number of cases where this kind of https://www.quora.com/Is-a-catch-all-exception-handler-*ever*-acceptable exception handling is good, though often left out. The most obvious case: it's not bad at all to catch all exceptions if you re-raise them. In Python you can re-raise the last exception by using raise without any arguments. Basically you are saying if (and only if) something goes wrong, do this, but still signal that something went wrong. python exception This case shouldn't be confused with finally:, which indicates code that should always be called, error or no error. An example of except:: try: cursor.execute("INSERT INTO table VALUES (%s, %s)", (a, b)) obj.setValues(a, b) except: cursor.rollback() raise And one for finally:: conn = pscyopg.connect('dbname=testdb') try: run_transaction(conn) finally: conn.close() But there's other cases. Anytime you won't be there to babysit a process, you need to handle unexpected exceptions. For a command-line utility, you can read python catching any the exception when it occurs, no big deal. But for a long-running or batch process you need to intelligently deal with exceptions. Also for processes that are run by non-developers: you want to capture the error information so a developer can look at it, and then try to keep going if you can. In these cases you usually want to be careful about putting in except: blocks like the cursor.rollback() example above -- these attempt to clean things up when something unexpected goes wrong, so that the process isn't left in an inconsistent state. Then at some fairly high level you actually handle (and don't re-raise) the exception. Most "frameworks" do this for you -- e.g., Tkinter, Webware, Zope, cgitb, etc. If you don't have a framework, you have to do it yourself. Here's a really simple handler that uses the traceback module: def catch_exceptions(func, *args, **kw): try: # We could return the result of the function, but it's # a bad idea to make use of that return value since it's # undefined when there's an exception; it's better for the # function to set a flag or write to some persistent # structure when it finishes successfully. func(*args, **kw) except Exception, e: f = open(log_file, 'a') f.write('-'*60 + '\n') traceback.print_exc(file=f) f.close() The logging module also has an
is a stylistic question rather than a practical one.I've written a bit of code (for purely internal purposes) which does something like this:def do_one(args): component, targ = args try: results = deploy[component](targ) except Exception, e: exception("Exception raised in do_one(%s): %s" % (targ, e)) results = (targ, False) info("do_one(%s) Completed" % targ) return results (where exception
and info
are aliased to the appropriate methods in a logging
instance and the deploy
is a dictionary containing the names of different server components as keys and corresponding deployment functions (mostly Pexpect
and subprocess.Popen
code) as values.do_one()
is called by the multiprocessing.Pool.map_async()
method as follows:pool = multiprocessing.Pool(processes=options.numjobs) results = pool.map_async(do_one, ((options.component, x ) for x in args)) while not results.ready(): process_log_messages(handler) debug("Waiting for results") results.wait(3) (For now each invocation of the code can only handle a homogenous mapping of targets to component. So that's set via command line option. I may add additional code later to look up each target in an external datastore to map it to the component that's supposed to be installed on it).The logging instance is using a "QueueHandler
" (pasted in from Python 3.2) and only the master process is posting things from that logging queue to the console (based on verbosity which is set in the options via the command line as handled by the standard library OptionsParser()
.My argument is that the map_async()
is calling functions in the pool as something like remote procedure calls and thus that those processes should not be allowed to throw their own exceptions. Those