Python Exception General Error
Contents |
Pages Local Site Map ------------------------ Rename Page Delete Page ------------------------ ------------------------ Remove Spam Revert to this revision ------------------------ SlideShow User Login Handling Exceptions The simplest way to handle exceptions is with a "try-except" block: 1 (x,y) = (5,0) 2 try: 3 z = x/y 4 except ZeroDivisionError: 5 print python exception message "divide by zero" If you wanted to examine the exception from code, you could
Python Print Exception
have: 1 (x,y) = (5,0) 2 try: 3 z = x/y 4 except ZeroDivisionError as e: 5 z = e python exception stack trace # representation: "
Syntax For Generic Except Clause In Python
usually you don't.In most cases, you want to be as specific as possible (CatchWhatYouCanHandle). In the first example above, if you were using a catch-all exception clause and a user presses Ctrl-C, generating a KeyboardInterrupt, you don't want the program to print "divide by zero". However, there are some situations where it's best to catch all errors. For example, suppose you are writing an extension module to a python custom exception web service. You want the error information to output the output web page, and the server to continue to run, if at all possible. But you have no idea what kind of errors you might have put in your code. In situations like these, you may want to code something like this: 1 import sys 2 try: 3 untrusted.execute() 4 except: # catch *all* exceptions 5 e = sys.exc_info()[0] 6 write_to_page( "
Error: %s
" % e ) MoinMoin software is a good example of where general error catching is good. If you write MoinMoin extension macros, and trigger an error, MoinMoin will give you a detailed report of your error and the chain of events leading up to it. Python software needs to be able to catch all errors, and deliver them to the recipient of the web page. Another case is when you want to do something when code fails: 1 try: 2 do_some_stuff() 3 except: 4 rollback() 5 raise 6 else: 7 commit() By using raise with no arguments, you will re-raise the last exception. A common place to use this would be to roll back a transaction, or undo operations. If it's a matter of cleanup that shoyou 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 you get
Python Try Without Except
while you are still learning Python: >>> while True print('Hello world') File "
Python Try Except Else
True print('Hello world') ^ SyntaxError: invalid syntax The parser repeats the offending line and displays a little ‘arrow' pointing at the earliest point try except python 3 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 at the function print(), since a colon https://wiki.python.org/moin/HandlingExceptions (':') 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 soon learn how to handle them in Python programs. Most exceptions https://docs.python.org/3/tutorial/errors.html are not handled by programs, however, and result in error messages as shown here: >>> 10 * (1/0) Traceback (most recent call last): File "
here for a quick overview of the site Help Center Detailed answers to any questions you might have Meta Discuss the workings http://stackoverflow.com/questions/2052390/manually-raising-throwing-an-exception-in-python and policies of this site About Us Learn more about Stack Overflow the company Business Learn more about hiring developers or posting ads with us Stack Overflow Questions Jobs Documentation http://www.ianbicking.org/good-catch-all-exceptions.html Tags Users Badges Ask Question x Dismiss Join the Stack Overflow Community Stack Overflow is a community of 6.2 million programmers, just like you, helping each other. Join them; python exception it only takes a minute: Sign up Manually raising (throwing) an exception in Python up vote 800 down vote favorite 189 How can I raise an exception in Python so that it can later be caught via an except block? python exception exception-handling share|improve this question edited Feb 3 '15 at 14:37 DavidRR 5,20472747 asked Jan 12 '10 at 21:07 python exception general TIMEX 41.2k201525826 add a comment| 3 Answers 3 active oldest votes up vote 787 down vote accepted How do I manually throw/raise an exception in Python? Use the most specific Exception constructor that semantically fits your issue. Be specific in your message, e.g.: raise ValueError('A very specific bad thing happened') Don't do this: Avoid raising a generic Exception, to catch it, you'll have to catch all other more specific exceptions that subclass it. Hiding bugs raise Exception('I know Python!') # don't, if you catch, likely to hide bugs. For example: def demo_bad_catch(): try: raise ValueError('represents a hidden bug, do not catch this') raise Exception('This is the exception you expect to handle') except Exception as error: print('caught this error: ' + repr(error)) >>> demo_bad_catch() caught this error: ValueError('represents a hidden bug, do not catch this',) Won't catch and more specific catches won't catch the general exception: def demo_no_catch(): try: raise Exception('general exceptions not caught by specific handling') except ValueError as e: print('we will not catch e') >>> demo_no_catch() 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 disagree with him, but there are a number of cases where this kind of 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. 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 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 i