Python Tutorial Learning (eight)--errors and Exceptions

Source: Internet
Author: User
Tags integer division

8. Errors and Exceptions errors and exceptions

We haven't started looking at error messages before. But if you walk along the way with routines, you'll find the error message. There are at least two types of errors in Python: syntax errors and exceptions (syntax errors and exceptions)

8.1. Syntax Errors Syntax error

Grammatical errors are grammatical errors, and grammatical errors are grammatical errors.

For example, keyword spelling errors, indentation errors, punctuation errors and so on, such as the following in the chestnut in the while loop in the time to miss the syntax error caused by the colon, note that the error is not only given a specific place of error,

The '^' intuitively gives the position.

' Hello World ' File ' <stdin> ', line 1, in? and True print ' Hello World ' ^syntaxerror:invalid synt Ax   
8.2. Exceptions Exceptions

Even though there is no grammatical error in the program, sometimes we still have a few moths, which is an anomaly. What I need to tell you here is that in Python, exceptions can be controlled and handled.

Lift a chestnut:

>>>10*(1/0)Traceback (most recent): File "<stdin>", line 1, in ? Zerodivisionerror: integer division or modulo by Zero>>> 4 + spam*3traceback (most recent Call last): File 1, in ? Nameerror: name ' spam ' is not defined>>>  ' 2 ' + 2traceback (most recent call last): File 1, in ? TypeError: cannot concatenate ' str ' and ' int ' objects        Above the chestnut inside caused an exception, the first is 0 as the divisor of the exception, the second is to refer to a non-existent variable caused by the exception, the third is different similar format of data addition exception

8.3. Handling of handling Exceptions anomalies

Python's usual exception handling is the use of try...except ... Combination, the associated program code that needs to be run is placed between the try except and the subsequent processing that causes the exception is placed in the code after except. Like this.

Try

Do something

Except

print ' ERROR appear while doing something '

Here we give the running flow of try except:

The try statement works as follows.

  • First, the try clause (the statement (s) between the try and except keywords) is executed.
  • If No exception occurs, the except clause is skipped and execution of the ' try statement ' is finished.
  • If An exception occurs during execution of the the TRY clause, the rest of the clause is skipped. Then if it type matches the exception named after the except keyword, the except clause are executed, and then ex Ecution continues after the try statement.
  • If An exception occurs which does don't match the exception named in the EXCEPT clause, it's passed on to outer TRY statements; If no handler is found, it's an unhandled exception and execution stops with a message as shown above.

This means that the order in which the code is run in the try expression is as follows:

First, the code between the try and except is executed directly, and if there is no exception, the expression in the except is not executed, and if the exception is generated, the expression after the code that generated the exception is terminated and then the exception is matched with the exception type in except. Match to the code that executes the except section.

If the given exception type in except does not match, then try except terminates with an error message.

Of course, if you don't want to deal with some of the exceptions that are generated, you can discard them directly, which should look like this in the program code:

Try

Do something

Except Exception, E: #except后面继承的异常类是可选字段, can also be omitted directly, because except default inheritance Exception (this is the base class for all exceptions)

Pass # This would do nothing

For a chestnut, choose to handle a class or classes of exceptions, and the remaining exceptions are simply discarded:

ImportSysTry:F=Open(' MyFile.txt ')S=F.ReadLine()I=Int(S.Strip())ExceptIOError as e: print "I/O error ({0}): {1}".  Format(e.  errno, e.  Strerror)except valueerror: print "Could not convert data to an integer." except: print "Unexpected error:", sys.  Exc_info() [0] raise             
The try except expression also has an optional else branch, which is used to continue executing the relevant code after try except no exception execution, noting that else must be placed after all except. This is useful in some cases, such as a chestnut, Output the file contents after successfully opening the file:
ForArgInchSys.Argv[1:]: try: f = Span class= "NB" >open (arg ' R ' ) Span class= "K" >except ioerror: print  ' cannot open ' arg else: print  Arglen ( f. Readlines ' lines ' f. Close ()               
8.4. The generation of raising Exceptions anomalies

Raise expression Run program forces an exception to be thrown, chestnuts come:

nameerror(' hithere ')?  Hithere      Temporary use of not much, here is a brief introduction of a little
8.5. user-defined Exceptions Custom exception

Do you have enough detail to dislike Python's own exception? You can also choose to customize some exceptions, such as this:

>>>ClassMyerror(Exception):...Def__init__(Self,Value):...Self.Value=Value...Def__str__(Self):...ReturnRepr(Self.Value)...>>>Try:...RaiseMyerror (2*2)  ... Span class= "K" >except myerror as e:  ... print  ' My exception occurred, value: ' e value ... my exception occurred, Value:4>>> raise  Myerror ( ' oops! ' ) traceback (most recent call last): File 1, in ? __main__. Myerror:  ' oops! '              
8.6. Defining clean-up Actions define ' finishing ' actions

The try expression has an optional expression, finally, which is always executed, whether or not an exception occurs, such as:

try:     ... Keyboardinterruptfinally:' Goodbye, world! ' ... Goodbye, world! keyboardinterrupt          Combined with the above, we can even do this:
Try
Do something
Except
Do annotherthing
Else
Do something after successed while trying
Finally
Always do something no matter success or failure
8.7. Predefined clean-up Actions What does that mean??? Orz ...

Of course, when I really need to know, I might have to figure out what this pile of ...

To drop a face:

Some objects define standard clean-up actions to being 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.

Open("myfile.txt"line,   

The problem with this code is, it leaves the file open for a indeterminate amount of time after the code have finished Executing. This isn't an issue in simple scripts, but can be a problem for larger applications. The with statement allows objects as files to being used in a-a-to-ensures they is always cleaned up promptly and correctly.

Open("MyFile.txt"FFline,     

After the statement is executed, the file F are always closed, even if a problem were encountered while processing The lines. Other objects which provide predefined clean-up actions would indicate this in their documentation.

The patience to read, probably to understand,
Pre-defined ' end ' work, and then explained, some of the problems may not be good, but the real place in a more complex environment may be a pit, for example, in a single file script, open a file does not close, there may be no problem, but if it is in the project to do so, It may cause problems. With makes these simple and rough and safe.

Chestnut inside, with open (XXX) as f: ... Execution is hard enough, the file F is always closed, even if the code is executed in the process of creating an exception, or is closed, respect good.

Python Tutorial Learning (eight)--errors and Exceptions

Related Article

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.