Python Learning Note Series----(vi) Errors and exceptions

Source: Internet
Author: User

Python has at least 2 different types of errors: syntax errors (Syntax Errors) and exceptions (Exceptions).

8.1 Syntax errors

This word should still be very necessary to know, hehe, grammatical errors, also known as parsing errors, is our most reluctant to take place the error, directly take the official website example:

 while ' Hello World '  "<stdin>" 1 in?        while ' Hello World '                   ^Syntaxerror:invalid Syntax

A syntax error prompts you to print a statement that appears in the syntax and then hit ' ^ ' in the statement to indicate the closest place to the syntax error. In the example, the quotation marks are missing before print (This is a dead loop ~ ~):

 while ' Hello World ' ... Hello World

8.2 Exceptions
A statement or an expression, even when compiled with no syntax errors, may be problematic at execution time, which is also known as an exception (non-fatal), and exceptions are usually handled in the program. Exceptions are of different types, common exception types are zerodivisionerror, nameerror and TypeError, and such exceptions are known as standard exceptions, defined in build-in. You can view built-in Exceptions. There is also a class of exceptions that are user-definable.

>>>Ten* (1/0) Traceback (most recent): File"<stdin>", line1,inch?Zerodivisionerror:integer division or modulo by zero>>>'2'+2Traceback (most recent): File"<stdin>", line1,inch?Typeerror:cannot concatenate'Str'and'int'Objects

8.3 Handling Exceptions

Direct to a more complete exception handling example: Open a TXT document, read the first line of data, converted to an int data type, if successful, print txt total number of lines, and finally close the document.

    Try: F= Open ('Test.txt','r+') s=f.readline () I=int(S.strip ()) except IOError asE:print'I/O error ({0}): {1}'. Format (e.errno,e.strerror) except Valueerror:print"could not convert data to integer"Except:print"Unexpected error:", Sys.exc_info () [0]    Else: Print'there have {0} lines in the file'. Format (len (F.readlines ()))finally: Print'end of the function'f.close ()

The Try statement handles the exception by doing this:

A. Preferred, the Try child statement (the statement between the try and the except keyword) is executed.

B. If no exception occurs, the EXCEPT clause is skipped.

C. If an exception occurs, the other statements that follow the try are skipped, and if the exception type matches after the except keyword, the except clause is executed.

D. If no exception occurs, the ELSE clause is executed. Else's role is to avoid the exception that is being initiated by capturing unprotected code.

The finally Sub -language executes before the TRY clause finishes executing, regardless of whether or not an exception occurs. When an exception occurs in a try clause that is not processed (or when it occurs in a except or else clause), the finally clause will throw an exception again when it finishes executing.

These basic grammars should also be fairly clear, and the documentation lists some of the things to be aware of:

First: When dealing with multiple exceptions at once, multiple exceptions need to be enclosed in parentheses.  

       except (runtimeerror typeerror): This is the right;except  runtimeerror, typeerror : The notation is wrong, because except valueerror, except valueerror as e. < EM id= "__mcedel" >
/span>

< Span class= "p" > second: last except Clause can have no exception type name, so that any undefined exception can be caught.

Third: When an exception occurs, it may also have some exception parameters. The exception name of the except statement can be followed by a parameter, which is bound to the exception instance, stored in the Instance.args, if the exception __str__() is defined, you can directly print out the parameters.

>>>Try: ..... raise Exception ('spam','eggs') ... except Exception asInst: ... print type (inst) # The exception instance ... print Inst.args # arguments storedinch. Args ... print inst # __str__ allows args to be printed directly ... x, y=Inst.args ... print'x =', x ... print'y =', y ...<type'exceptions. Exception'>('spam','eggs')('spam','eggs') x=Spamy= Eggs

8.4 User-defined exceptions

User-defined exceptions need to inherit the exception class, the official website example is as follows:

>>>classMyerror (Exception): ... def __init__ (self, value): ... self.value=value ... def __str__ (self): ...returnrepr (self.value) ...>>>Try: ..... raise Myerror (2*2) ... except Myerror ase: ... print'My exception occurred, value:', E.value ... My exception occurred, value:4>>> Raise Myerror ('oops!') Traceback (most recent): File"<stdin>", line1,inch?__main__. Myerror:'oops!'

In this example, the Init method is rewritten to create a new member variable, value.

8.5 defined cleanup behavior

When this object is no longer needed, some objects have already defined the standard cleanup behavior, regardless of whether the object operation succeeds or fails; The common example is to open the document:

 for  in open ("myfile.txt"):    print line,

The problem with this code is that after this code is executed, the document is in the open state time is indeterminate, in a small script, this is not a very serious problem, but if it is part of a large application, the problem will be magnified. Using the WITH statement allows classes like files to be cleaned up after they are used (freeing some resources, as I understand it):

With open ("myfile.txt" as f:     f:        print line,

With this line of code, F is already in the close state. Even if every line in the read file encounters an error, it will be shut down.

 

Python Learning Note Series----(vi) 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.