Home >Backend Development >Python Tutorial >Python 2.7 Basic Tutorial: Errors and Exceptions
.. _tut-errors:
====================================
Errors and Exceptions Errors and Exception
==================================
Until now error messages haven't been more than mentioned , but if you have tried
out the examples you have probably seen some. There are (at least) two
distinguishable kinds of errors: *syntax errors* and *exceptions*.
No further discussion so far Error messages, but
may have encountered some in the examples you have experimented with. There are (at least) two kinds of errors in Python: *syntax errors* and *exceptions*
.
.. _tut-syntaxerrors:
Syntax Errors Syntax errors
========================
Syntax errors, also known as parsing errors, are Perhaps the most common kind of
complaint you get while you are still learning Python:
Grammar errors, also known as interpretation errors, may be the most common kind of
complaint you get while you are still learning Python::
>>> while True print 'Hello world'
'File "
' 'Hello world' the offending line and displays a 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 at the keyword :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.
The parser repeats the line with the error and displays a small "arrow" at the earliest error found in the line. The error
(at least the one that is detected) occurs where the arrow *points*. The error in the example appears on the keyword
:keyword:`print` because there is a colon missing before it ( ``':'`` ). The file name and line number will also be displayed,
so you can know which script the error comes from and where it is.
.. _tut-exceptions:
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 are not handled by
programs, however, and result in error messages as shown here:
Even if a statement is completely grammatically correct, an error may occur when trying to execute it. Errors detected while the program is running are called exceptions. They usually do not cause fatal problems, and you will soon learn how to control them in Python programs. Most exceptions will not be handled by the program, but will display an error message::
>>> 10 * (1/0)
Traceback (most recent call last):
File "< ;stdin>", line 1, in ?
ZeroDivisionError: integer division or modulo by zero
>>> 4 + spam*3
Traceback (most recent call last):
File " NameError: name 'spam' is not defined >>> '2' + 2 Traceback (most recent call last): File " TypeError: cannot concatenate 'str' and 'int' objects The last line of the error message indicates what happened. Exceptions come in different types, and the type is printed as part of the message: the types in the example are :exc:`ZeroDivisionError`, :exc:`NameError` and :exc:`TypeError`. The string printed as the exception type is the name of the built-in exception that occurred. This is true for all built-in exceptions, but need not be true for user-defined exceptions (although it is a useful convention). Standard exception names are built-in identifiers (not reserved keywords ). The last line of the error message indicates what error occurred. Exceptions also have different types. The exception types are displayed as part of the error message: the exceptions in the example are zero division error ( :exc:`ZeroDivisionError` ), naming error ( :exc:`NameError`) and Type Error ( :exc:`TypeError` ). When printing error information, the exception type is used as the built-in name of the exception Show. This is true for all built-in exceptions, but not necessarily for user-defined exceptions (although this is a useful convention). Standard exception names are built-in identifiers (no reserved keywords). The rest of the line provides detail based on the type of exception and what caused it. The rest of the line provides detail based on the type of exception and what caused it. The preceding part of the error message shows the context where the exception happened, in the form of a stack traceback. In general it contains a stack traceback listing source lines; however, it will not display lines read from standard input. The first half of the error message lists the location where the exception occurred in the form of a stack. Normally the source code lines are listed on the stack, however, source code coming from standard input is not displayed. :ref:`bltin-exceptions` lists the built-in exceptions and their meanings. :ref:`bltin-exceptions` lists the built-in exceptions and their meanings. .. _tut-handling: Handling Exceptions Control exceptions ============================ It is possible to write programs that handle selected exceptions. Look at the following example, which asks the user for input until a valid integer has been entered, but allows the user to interrupt the program (using :kbd:`Control-C` or whatever the operating system supports); note that a user-generated interruption is signaled by raising the :exc:`KeyboardInterrupt` exception. : Programs can be written to control known exceptions. See the example below, which requires the user to enter information until a valid integer is obtained, and allows the user to interrupt the program (using :kbd:`Control-C` or any other operation supported by the operating system); required Note that user-generated interrupts will throw the :exc:`KeyboardInterrupt` exception. :: >>> while True: ... try: ... x = int(raw_input("Please enter a number: ")) ... break .. . except ValueError: ... print "Oops! That was no valid number. Try again..." ... The :keyword:`try` statement works as follows. :keyword:` The try` statement works as follows. * First, the *try clause* (the statement(s) between the :keyword:`try` and :keyword:`except` keywords) is executed. The part between the :keyword:`try` and :keyword:`except` keywords). * If no exception occurs, the *except clause* is skipped and execution of the :keyword:`try` statement is finished. If no exception occurs, the *except clause* is skipped and execution of:keyword:`try` After the statement is executed, it is ignored. * If an exception occurs during execution of the try clause, the rest of the clause is skipped. Then if its type matches the exception named after the :keyword:`except` keyword, the except clause is executed, and then execution continues after the :keyword:`try` statement. If an exception occurs during the execution of the try clause, the rest of the clause will be ignored. If the exception matches the exception type specified after the :keyword:`except` keyword, the corresponding except clause will be executed. Then continue executing the code after the :keyword:`try` statement. * If an exception occurs which does not match the exception named in the except clause, it is passed on to outer :keyword:`try` statements; if no handler is found, it is an *unhandled exception* and execution stops with a message as shown above. If an exception occurs and there is no matching branch in the except clause, it will be passed to the upper level:keyword:`try` statement . If the corresponding processing statement is still not found in the end, it becomes an *unhandled exception*, terminates the program, and displays a prompt message. A :keyword:`try` statement may have more than one except clause, to specify handlers for different exceptions. At most one handler will be executed. Handlers only handle exceptions that occur in the corresponding try clause, not in other handlers of the same :keyword:`try` statement. An except clause may name multiple exceptions as a parenthesized tuple, for example: an :keyword:`try` statement may contain multiple except clauses , specifying the processing of different exceptions respectively. At most, only one branch will be executed. The exception handler will only handle the corresponding try clause. Exceptions that occur in the same :keyword:`try` statement, exceptions that occur in other clauses will not be handled . An except clause may list multiple exception names in parentheses, for example:: ... except (RuntimeError, TypeError, NameError): ... pass 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): The last except clause can omit the exception name and use it as a wildcard. Be sure to use this method with caution, because it is likely to mask the real program error and prevent people from discovering it! It can also be used to print a line of error information and then rethrow the exception (which allows the caller to handle the exception better):: import sys 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] ... print inst print ' y =', y ... ('spam', 'eggs') ('spam', 'eggs') x = spam y = eggs If an exception has an argument, it is printed as the last part ('detail') of the message for unhandled exceptions. For unhandled exceptions, if it has an argument, do It will be printed as the last part of the error message ("details"). Exception handlers don't just handle exceptions if they occur immediately in the try clause, but also if they occur inside functions that are called (even indirectly) in the try clause. For example: Exception handlers Not only can exceptions that occur directly in the try clause be handled, even if an exception occurs in the function called (even indirectly), it can also be handled. For example:: >>> def this_fails(): ... x = 1/0 ... >>> try: ... this_fails() ... except ZeroDivisionError as detail: ... print 'Handling run-time error:', detail ... Handling run-time error: integer division or modulo by zero .. _tut- raising: Raising Exceptions Throwing exceptions ============================== The :keyword:`raise` statement allows the programmer to force a specified exception to occur. For example: The programmer can use the :keyword:`raise` statement to force the specified exception to occur. For example:: >>> raise NameError('HiThere') Traceback (most recent call last): File " NameError: HiThere The sole argument to :keyword:`raise` indicates the exception to be raised. This must be either an exception instance or an exception class (a class that derives from :class:`Exception`). To throw The exception raised is identified by the unique parameter of :keyword:`raise`. It must be an exception instance or an exception class (a class inherited from :class:`Exception`). If you need to determine whether an exception was raised but don't intend to handle it, a simpler form of the :keyword:`raise` statement allows you to re-raise the exception: if you If you need to know whether an exception is thrown, but don't want to handle it, the :keyword:`raise` statement allows you to easily re-throw the exception. >>> try: ... raise NameError('HiThere') ... except NameError: ... print 'An exception flew by!' ... raise ... An exception flew by! Traceback (most recent call last): File " NameError: HiThere .. _tut-userexceptions: User-defined Exceptions User-defined exceptions ======================================== Programs may name their own exceptions by creating a new exception class (see :ref:`tut-classes` for more about Python classes). Exceptions should typically be derived from the :exc:`Exception` class, either directly or indirectly. For example: You can name your own exceptions by creating a new exception type in the program (for the content of Python classes, please see:ref:`tut-classes`). Exception classes should usually be derived directly or indirectly from the :exc:`Exception` class, for example:: >>> class MyError(Exception): ... def __init__(self, value): A ... Self.value = Value ... def __Str __ (Self): ... Return Repr (Self.value) ... & gt; & gt; try: : : : : : : : : : : : : : Traceback (most recent call last): File " __main__.MyError: 'oops!' In this example, the default :meth:`__init__` of : class:`Exception` has been overridden. The new behavior simply creates the *value* attribute. This replaces the default behavior of creating the *args* attribute. In this example, :class:`Exception` The default :meth:`__init__` is overridden. New way to easily create value properties. This replaces the original way of creating *args* attributes. Exception classes can be defined which do anything any other class can do, but are usually kept simple, often only offering a number of attributes that allow information about the error to be extracted by handlers for the exception. When creating a module that can raise several distinct errors, a common practice is to create a base class for exceptions defined by that module, and subclass that to create specific exception classes for different error conditions: Exception classes can Define anything that can be defined in any other class, but usually to keep it simple, only a few attribute information is added to it for exception handling handlers to extract. If a newly created module needs to throw several different errors, a common approach is to define an exception base class for the module, and then derive corresponding exception subclasses for different error types. :: class Error(Exception): """Base class for exceptions in this module.""" pass class InputError(Error): """Exception raised for errors in the input. Attributes: : self.expr = expr prev -- state at beginning of transition next -- attempted new state . self.next = next self.msg = msg Most exceptions are defined with names that end in "Error," similar to the naming of the standard exceptions. Error" at the end. Many standard modules define their own exceptions to report errors that may occur in functions they define. More information on classes is presented in chapter :ref:`tut-classes`. Many standard modules are defined in Their own exceptions to report errors that may occur in the functions they define. See chapter :ref:`tut-classes` for further information about classes. .. _tut-cleanup: Defining Clean-up Actions Defining clean-up actions ================================ ====================== The :keyword:`try` statement has another optional clause which is intended to define clean-up actions that must be executed under all circumstances. For example: :keyword:`try` statement has another optional clause, the purpose is to define the function that must be executed under any circumstances. For example:: >>> try: ... raise KeyboardInterrupt ... finally: ... print 'Goodbye, world!' ... Goodbye, world! Traceback (most recent call last): File " KeyboardInterrupt A *finally clause* is always executed before leaving the :keyword:`try` statement , whether an exception has occurred or not. When an exception has occurred in the :keyword:`try` clause and has not been handled by an :keyword:`except` clause (or it has occurred in a :keyword:`except` or :keyword:`else` clause), it is re-raised after the :keyword:`finally` clause has been executed. The :keyword:`finally` clause is also executed "on the way out" when any other clause of the :keyword:`try` statement is left via a :keyword:`break`, :keyword :`continue` or :keyword:`return` statement. A more complicated example (having :keyword:`except` and :keyword:`finally` clauses in the same :keyword:`try` statement works as of Python 2.5): No matter whether an exception occurs or not, the *finally clause* will always be executed after the program leaves :keyword:`try`. When an exception not caught by :keyword:`except` occurs in a :keyword:`try` statement (or it occurs in a :keyword:`except` or :keyword:`else` clause), in It will be re-thrown after the :keyword:`finally` clause is executed. If the :keyword:`try` statement is exited by :keyword:`break`, :keyword:`continue` or :keyword:`return`, the :keyword:`finally` clause will also be executed. Here is a more complex example (the :keyword:`except` and :keyword:`finally` clauses in the same :keyword:`try` statement work the same as in Python 2.5):: >>> def divide(x, y): ... try: ... result = x / y ... except ZeroDivisionError: ... print "division by Zero! "l ... Else: ... Print" Result is ", Result ... Finally: ... Print" Executing Finally Clause " ... & gt; & gt ;> divide(2, 1) result is 2 executing finally clause >>> divide(2, 0) division by zero! executing finally clause >> > divide("2", "1") executing finally clause Traceback (most recent call last): File " File " TypeError: unsupported operand type(s) for /: 'str' and 'str' As you can see, the :keyword:`finally` clause is executed in any event. The :exc:`TypeError` raised by dividing two strings is not handled by the :keyword:`except` clause and therefore re-raised after the :keyword:`finally` clause has been executed. as you As you can see, the :keyword:`finally` clause will execute in any case. :exc:`TypeError` is thrown when two strings are divided and is not caught by the :keyword:`except` clause, so it is re-thrown after the :keyword:`finally` clause is executed. . In real world applications, the :keyword:`finally` clause is useful for releasing external resources (such as files or network connections), regardless of whether the use of the resource was successful. In real world applications In applications, the :keyword:`finally` clause is used to release external resources (files or network connections, etc.) regardless of whether there are errors during their use. .. _tut-cleanup-with: Predefined Clean-up Actions ============================ ============================ Some objects define standard clean-up actions to be undertaken when the object is no longer needed , regardless of whether or not the operation using the object succeeded or failed. Look at the following example, which tries to open a file and print its contents to the screen. : Some objects define standard cleanup behavior , regardless of whether the object operation is successful or not, it will take effect when the object is no longer needed. The following example attempts to open a file and print its contents to the screen. :: for line in open("myfile.txt"): print line The problem with this code is that it leaves the file open for an indeterminate amount of time after the code has finished executing. This is not an issue in simple scripts, but can be a problem for larger applications. The :keyword:`with` statement allows objects like files to be used in a way that ensures they are always cleaned up promptly and correctly. : The problem with this code is that the open file is not closed immediately after the code is executed. This is fine in simple scripts , but can cause problems in larger applications. The :keyword:`with` statement allows objects such as files to be cleaned up in a timely and accurate manner. :: with open("myfile.txt") as f: for line in f: print line After the statement is executed, the file *f* is always closed, even if a problem was encountered while processing the lines. Other objects which provide predefined clean-up actions will indicate this in their documentation. After the statement is executed, the file *f* will always be closed, even if an error occurs while processing the data in the file. If other objects provide predefined cleaning behaviors, please check their documentation. The above is the basic tutorial of Python 2.7: errors and exceptions. For more related content, please pay attention to the PHP Chinese website (www.php.cn)!