Python Error Message Tutorial
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 Exception Stack Trace
example, the error is detected 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 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 python print exception wanted to examine the exception from code, you could have: 1 (x,y) = (5,0)
Python Try Without Except
2 try: 3 z = x/y 4 except ZeroDivisionError as e: 5 z = e # representation: "
Python Try Except Else
print z # 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 https://docs.python.org/2.7/tutorial/errors.html 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 web service. You want the error information to output the output web page, and https://wiki.python.org/moin/HandlingExceptions 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 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 raiand VariablesOperatorsinput and raw_input via the keyboardConditional StatementsWhile LoopsFor LoopsFormatted outputOutput with PrintSequential Data TypesDictionariesSets and Frozen SetsShallow and Deep CopyFunctionsRecursion and http://www.python-course.eu/exception_handling.php Recursive FunctionsTests, DocTests, UnitTestsMemoization with DecoratorsPassing ArgumentsNamespacesGlobal vs. Local VariablesFile ManagementModular Programming and ModulesIntroduction in Regular ExpressionsRegular Expressions, AdvancedLambda Operator, Filter, Reduce and MapList https://en.wikibooks.org/wiki/A_Beginner's_Python_Tutorial/Exception_Handling ComprehensionGeneratorsException HandlingObject Oriented ProgrammingInheritance ExampleSlotsClasses and Class CreationRoad to MetaclassesMetaclassesMetaclass Example: Count Function Calls Exception from the Rule "There are two great rules python exception of life, the one general and the other particular. The first is that everyone can in the end, get what he wants, if he only tries. That is the general rule. The particular rule is that every individual is, more or less, an exception to the python error message rule." Samuel Butler Delicate Handling "The finest qualities of our nature, like the bloom on fruits, can be preserved only by the most delicate handling. Yet we do not treat ourselves nor one another thus tenderly." Henry David Thoreau Supported by: Python Training Courses in Canada This topic in German / Deutsche Übersetzung: AusnahmebehandlungPython 2.7This tutorial deals with Python Version 2.7This chapter from our course is available in a version for Python3: Exception HandlingClassroom Training Courses This website contains a free and extensive online tutorial by Bernd Klein. If you are interested in an instructor-led classroom training in Canada or the US, you may have a look at the Python courses by Bernd Klein at Bodenseo © kabliczech - Fotolia.com Overview of Python courses by Bernd Klein. The Truth in Errors "The first step towards amendment is t
navigation, search Contents 1 Introduction 2 Bugs - Human Errors 3 Exceptions - Limitations of the Code 4 Endless Errors Introduction[edit] If you haven't seen them before, you're not trying hard enough. What are they? Errors. Exceptions. Problems. Know what I'm talking about? I got it with this program: Code Example 1 - buggy program def menu(list, question): for entry in list: print 1 + list.index(entry), print ") " + entry return raw_input(question) - 1 # running the function # remember what the backslash does answer = menu(['A','B','C','D','E','F','H','I'],\ 'Which letter is your favourite? ') print 'You picked answer ' + (answer + 1) This is just an example of the menu program we made earlier. Appears perfectly fine to me. At least until when I first tried it. Run the program, and what happens? Bugs - Human Errors[edit] The most common problems with your code are of your own doing. Sad, but true. What do we see when we try to run our crippled program? Code Example 2 - error message Traceback (most recent call last): File "/home/steven/errortest.py", line 10, in -toplevel- answer = menu(< I'll snip it here >) File "/home/steven/errortest.py", line 6, in menu return raw_input(question) - 1 TypeError: unsupported operand type(s) for -: 'str' and 'int' Say what? What Python is trying to tell you (but struggling to find a good word for it) is that you can't join a string of letters and a number into one string of text. Let's go through the error message and have a look at how it tells us that: File "/home/steven/errortest.py", line 10, in -toplevel- tells us a couple of things. File "/home/steven/errortest.py" tells us which file the error occured in. This is useful if you use lots of modules that refer to each other. line 10, in -toplevel- tells us that it is in line # 10 of the file, and in the top level (that is, no indentation). answer = menu(['A','B','C','D','E','F','H','I'],'Which letter is your favourite? ') duplicates the code where the error is. Since this line calls a function, the next two lines describe where in the function the error occured. TypeError: unsupported operand type(s) for -: 'str' and 'int' tells you the error. In this case, it is a 'TypeError', where you tried to subtract incompatible variables. There are multiple file and code listings for a single error, because the error occured with the interaction of two lines of code (e.g. when using a function, the error occured on the line where the function was called, AND the line in the function where things went wrong). Now that we know what the problem is, how do we fix it. Well, the error message has isolated where the problem is, so we'll only concentrate