PYTHON14: Errors and exceptions

Source: Internet
Author: User

In the process of programming, it is always impossible to avoid handling exceptions, which can also be errors or occasional exceptions, and Python provides an effective mechanism for dealing with these situations.

Syntax error

Syntax errors, or parsing errors, may be the most common mistakes you'll encounter in learning Python:

>>> while True print (' Hello world ')  File "<stdin>", line 1, in?    While True print (' Hello world ')                   ^syntaxerror:invalid syntax
The parser specifies the file name and the wrong line, and uses a ' ^ ' to point to the location where the error occurred: In this example, the error is detected in the function print (), because it was missing the ': '.

Abnormal

Even if the statement is syntactically correct, it may cause an error when it is executed. The error during execution is called an exception, which tells you how to handle the exception in Python. The following shows some of the exception information:

>>> (1/0) Traceback (most recent):  File "<stdin>", line 1, in? Zerodivisionerror:division by zero>>> 4 + spam*3traceback (most recent call last):  File "<stdin>", Lin E 1, in?  Nameerror:name ' spam ' isn't defined>>> ' 2 ' + 2Traceback (most recent call last):  File "<stdin>", line 1, in? Typeerror:can ' t convert ' int ' object to str implicitly
The last line of the error message indicates the cause of the error. There are many different types of exceptions, which are also printed as part of the information: in the example above, there are Zerodivisionerror, Nameerror, and TypeError, where the print is the name of the exception, and all the inline exceptions are printed exception names. However, user-defined exceptions are not necessarily (although this is a useful practice).
The remainder of the last line of information provides the details of the exception, including the cause of the exception.
The previous section of the error message shows the context in which the exception occurred, including stack information.

Handling Exceptions

The specified exception can be handled in the code, as shown in the following example, requesting user input until a valid integer is obtained, but allowing the user to interrupt the program (CONTROL-C or other operating system support), the user interrupt program usually causes the Keyboardinterrupt exception:

>>> while true:try:x = Int (input ("Please enter a number:")) breakexcept valueerror:print ("oops!  That is no valid number.  Try again ... ")
The Try statement works as follows:
1) first The block of statements between try and except will be executed;
2) If no exception occurs, the EXCEPT clause is skipped and the try statement block is executed;
3) If an exception occurs when a try statement block executes, the remainder of the statement block is skipped, and if the type of the exception matches the except corresponding exception name, the EXCEPT clause is executed;
4) If an exception occurs and there is no matching exception name in the EXCEPT clause, it is passed to the outer try statement block; If no processor is found, it is an unhandled exception, execution stops and prints the exception information.
A try statement can have multiple except clauses that provide different processors for different exceptions, and at most one processor at a time is executed. A except can correspond to multiple exceptions, such as:

Except (RuntimeError, TypeError, Nameerror):
Pass

The last except clause can omit the exception name as a wildcard character. Doing so requires great care, because it's easy to block out real programming errors. It can also be used to print exception information and then re-throw the exception:

Import Systry:    f = open (' myfile.txt ')    s = f.readline ()    i = Int (S.strip ()) except OSError as err:    print (" OS error: {0} ". Format (ERR)) except ValueError:    print (" Could not convert data to an integer. ") Except:    print ("Unexpected error:", Sys.exc_info () [0])    raise
Try ... except also has an optional ELSE clause that must be followed by all except clauses. You can use it when you want to execute some code without an exception in the try. For example:

For ARG in sys.argv[1:]:    try:        f = open (arg, ' R ')    except IOError:        print (' Cannot open ', arg)    else:< C12/>print (ARG, ' has ', Len (F.readlines ()), ' lines ')        f.close ()
When an exception occurs, it can have an associated value, called an exception parameter. The residuals and types of the parameters depend on the exception type.
The exception clause can specify a variable after the exception name, which is bound to an exception instance, and the value of the exception parameter is saved in Instance.args. The exception instance defines __str__ () to facilitate direct printing of parameters. You can also instantiate an exception, throw it, and add the desired property to it:

>>> try:raise Exception (' spam ', ' eggs ') except Exception as Inst:print (Type (inst))    # The Exception Instanceprint (Inst.args)     # Arguments stored in. Argsprint (inst)          # __str__ allows args to be printed directly, # BU T may is overridden in exception subclassesx, y = Inst.args     # unpack Argsprint (' x = ', x) <class ' Exception ' > (' Spa M ', ' eggs ') (' spam ', ' eggs ') x = Spam
If an exception has parameters, if the exception is not processed, the parameter is printed as the last part of the information.
Exception blocks not only handle exceptions that occur in a try clause, they also handle exceptions that occur in functions that are called in a try. For example:

>>> def this_fails ():        x = 1/0   >>> try:        this_fails ()    except Zerodivisionerror as err:        print (' Handling run-time error: ', err)   Handling Run-time Error:int division or modulo by zero

Raise clause

Use raise to throw a specified exception, for example:

>>> Raise Nameerror (' Hithere ') Traceback (most recent call last):  File "<stdin>", line 1, in? Nameerror:hithere
The raise parameter is the exception that is thrown, and the argument must be an exception instance or an exception class (Exception subclass).
If you need to determine if an exception has been thrown, but do not want to handle it, you can use raise to re-throw the exception:

>>> try:        raise Nameerror (' Hithere ')    except Nameerror:        print (' An exception flew by! ')        Raise an   exception flew by! Traceback (most recent):  File ' <stdin> ', line 2, in? Nameerror:hithere

User-defined exceptions

If the built-in exception does not meet your requirements, you will need to create your own exception class. The custom exception class should be a subclass of exception (direct or indirect). For example

>>> class Myerror (Exception):        def __init__ (self, value):            self.value = value        def __str__ (self):            return repr (self.value)   >>> try:        raise Myerror (2*2)    except Myerror as E:        print (' My Exception occurred, value: ', E.value) My exception occurred, value:4>>> raise Myerror (' oops! ') Traceback (most recent):  File "<stdin>", line 1, in? __main__. Myerror: ' oops! '
In this example, the exception default __init__ () method is overloaded, and the new behavior creates a Value property, which replaces the default behavior of the Args property.
The exception class can do anything else, but it's best to keep the exception class simple, usually defining only the information necessary to reflect the error. When creating a module that can throw many different exceptions, one convention is to create a base class of exceptions, and then other subclasses to represent different errors.

Class Error (Exception): "" "Base class for exceptions in the This    module.    " " Passclass Inputerror (Error): "" "    Exception raised for errors in the input.    Attributes:        expression--input expression in which the error occurred        message--Explanation of the error "" "    def __init__ (self, expression, message):        self.expression = expression        self.message = MessageClass Transitionerror (Error): "" "raised when an    operation attempts a state transition that's not    allowed.    Attributes:        previous-state at beginning of transition        next – attempted new state        message--explanation of why the specific transition are not allowed    "" "    def __init__ (self, previous, Next, message):        Self.previo US = previous        Self.next = next        self.message = message
Most of the exception names end with "Error", similar to the naming of standard exceptions.
Usually standard modules define their own exceptions, and users report errors that occur in their top function.

Finally

There is another optional clause, the FINALLY clause, that defines the code that executes in any case, typically for cleanup operations, such as:

>>> try:        raise Keyboardinterrupt    finally:        print (' Goodbye, world! ')   Goodbye, world! Keyboardinterrupt
The finally clause always executes at the left of the try block, regardless of whether an exception occurred. When an exception appears in a try block and is not handled by the EXCEPT clause (or appears in the except or else clause), it is re-thrown after the finally clause is executed. The finally clause is also executed when the try block exits due to break, continue, or return. Here is an example of a more complex point:

>>> def divide (x, y):        try:            result = x        /y except Zerodivisionerror:            print ("division by Zero!")        Else:            print ("result is", result)        finally:            print ("executing finally clause") >>> divide (2, 1 ) result is a 2.0executing finally clause>>> divide (2, 0) division by zero!executing finally clause>>> Divi De ("2", "1") executing finally Clausetraceback (most recent):  File ' <stdin> ', line 1, in?  File "<stdin>", line 3, in dividetypeerror:unsupported operand type (s) for/: ' STR ' and ' str '
As you can see, the finally clause is executed under any circumstances. The typeerror caused by dividing two strings is not handled by the EXCEPT clause, and is therefore re-thrown after finally execution.
In real-world applications, the finally clause is useful, and is often used to free resources (such as files or network connections) without worrying about exceptions in the use of resources.

Pre-defined cleanup behavior

Some objects define standard cleanup behavior, which is called when the object is no longer needed, and does not care if the operation using the object succeeds. Look at the example below and try to open a file and print its contents:

For On open ("MyFile.txt"):    print (line, end= "")
The problem with this code is that the code does not close the file after execution, and in a simple script this is not a problem, but it can be problematic in large applications. The WITH clause ensures that a file (or other resource) is always closed after it is used:

With open ("MyFile.txt") as F:    for line in F:        print (line, end= "")
When the statement finishes executing, the file F is always closed, even if an exception occurs during execution. Like files This provides a predefined cleanup behavior object that is described in the documentation.

PYTHON14: Errors and exceptions

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.