Python Error Handling Code
Contents |
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 python exception class of complaint you get while you are still learning Python: >>> while True print
Python Exception Message
'Hello world' File "
Python Custom Exception
and are not unconditionally fatal: you will 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 "
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 "divide by zero" If you wanted to python try without except examine the exception from code, you could have: 1 (x,y) = (5,0) 2 try: 3 syntax for generic except clause in python z = x/y 4 except ZeroDivisionError as e: 5 z = e # representation: "
Python Try Except Else
output: "integer division or modulo by zero" General Error Catching Sometimes, you want to catch all errors that could possibly be generated, but usually you don't.In most cases, you want to be as specific as possible (CatchWhatYouCanHandle). https://docs.python.org/2.7/tutorial/errors.html 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 web service. You want the error information to output the output web page, and the server to continue to run, if https://wiki.python.org/moin/HandlingExceptions 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 should be run regardless of success or failure, then you would do: 1 try: 2 do_some_stuff() 3 finally: 4 cleanup_stuff() Finding Specific Exception Names Standard exceptions that can be raised are detailed at: http://docs.python.org/library/exceptions.html Look to class documentation to find out what exceptioCleaner Python: Use Exceptions Many programmers have had it drilled into their head that exceptions, in any language, should only be used in truly exceptional https://jeffknupp.com/blog/2013/02/06/write-cleaner-python-use-exceptions/ cases. They're wrong. The Python community's approach to exceptions leads to http://www.pythonforbeginners.com/error-handling/python-try-and-except cleaner code that's easier to read. And that's without the monstrous hit to performance commonly associated with exceptions in other languages. EDIT: Updated with more useful exception idioms Using exceptions to write cleaner code? When I talk about "using exceptions", I'm specifically not referring to creating python exception some crazy exception hierarchy for your package and raising exceptions at every possible opportunity. That will most certainly lead to unmaintainable and difficult to understand code. This notion has been widely discussed and is well summarized on Joel Spolsky's blog. Note: Python avoids much of the tension of the "error codes vs exceptions" argument. Between the ability to python error handling return multiple values from a function and the ability to return values of different types (e.g. None or something similar in the error case) the argument is moot. But this is besides the point. The style of exception usage I'm advocating is quite different. In short: take advantage of Python built-ins and standard library modules that already throw exceptions. Exceptions are built in to Python at the lowest levels. In fact, I guarantee your code is already using exceptions, even if not explicitly. Intermezzo: How the for statement works Any time you use for to iterate over an iterable (basically, all sequence types and anything that defines __iter__() or __getitem__()), it needs to know when to stop iterating. Take a look at the code below: words = ['exceptions', 'are', 'useful'] for word in words: print(word) How does for know when it's reached the last element in words and should stop trying to get more items? The answer may surprise you: the list raises a StopIteration exception. In fact, all iterables follow th
how to handle those. Exception handling allows us to continue our program (or terminate it) if an exception occurs. Error Handling Error handling in Python is done through the use of exceptions that are caught in try blocks and handled in except blocks. Try and Except If an error is encountered, a try block code execution is stopped and transferred down to the except block. In addition to using an except block after the try block, you can also use the finally block. The code in the finally block will be executed regardless of whether an exception occurs. Raising an Exception You can raise an exception in your own program by using the raise exception [, value] statement. Raising an exception breaks current code execution and returns the exception back until it is handled. Example A try block look like below try: print "Hello World" except: print "This is an error message!" Exception Errors Some of the common exception errors are: IOError If the file cannot be opened. ImportError If python cannot find the module ValueError Raised when a built-in operation or function receives an argument that has the right type but an inappropriate value KeyboardInterrupt Raised when the user hits the interrupt key (normally Control-C or Delete) EOFError Raised when one of the built-in functions (input() or raw_input()) hits an end-of-file condition (EOF) without reading any data Example Let's have a look at some examples using exceptions. except IOError: print('An error occured trying to read the file.') except ValueError: print('Non-numeric data found in the file.') except ImportError: print "NO module found" except EOFError: print('Why did you do an EOF on me?') except KeyboardInterrupt: print('You cancelled the operation.') except: print('An error occured.') There are a number of b