Learn to write: Python errors, exceptions, assertions

Source: Internet
Author: User

1. Error

(1) Syntax error

Syntax errors indicate that there is a structural error in the software, which cannot be interpreted by the interpreter or the compiler cannot compile. These errors must be corrected before the program executes.

(2) Logic error

A logic error may be caused by an incomplete or illegal input. It may also be that the logic cannot be generated, the calculation, or the process required to output the result cannot be performed

2. Exceptions

(1) When Python detects an error, the interpreter indicates that the current stream has failed to execute, and an exception occurred.

(2) An exception is a behavior that is taken outside of the normal flow of control because of an error in the program. This behavior is divided into two stages, the first is the error that caused the exception, then the detection (and the possible measures) phase

Abnormal
Describe
Nameerror
Object not declared/initialized
Indexerror
This index is not in the sequence
SyntaxError
Syntax error
Keyboardinterrupt
User Interrupt execution
Eoferror
No internal key input, EOF Mark reached
IOError
Input/output operation failed

3. Exception Handling

3.1 try-except

Put the statement you think is likely to occur in the inside of the try to execute, want to catch what exception, put the exception into the except inside, how to deal with the exception after capture, the processing of the statement to write to except below, containing the finally statement, except statement, try statement, Else statement, with statement, as follows.

#!/usr/bin/env Pythonimport timeimport sysfor i in Range (1,11): Sys.stdout.write ("\r%s"% i) Sys.stdout.flush () t Ry:time.sleep (1) except Keyboardinterrupt:pass

You can also have more than one expect statement, whether it is CTRL + C or ctrl+d or direct return or input is not an integer will have the relevant hints, example 1 is to show the user, will output the corresponding message. Example 2 is for the programmer to see, will output a hint message and program error messages are also output. Instance 3 captures all exceptions and then outputs a single specified sentence.

Example one: #!/usr/bin/env pythontry:    num = int (raw_input ("Number: ")) except valueerror:    print  "error: you must input a  Number "except  (keyboardinterrupt, eoferror):     //If multiple exceptions are caught at the same time, parentheses are required, otherwise      print  "user cancelled           Example of a variable that is considered to be the reason for saving the error two:    #!/usr/bin/env pythontry:    num =  Int (raw_input ("number: ")) except valueerror, reason:             //, the variable on the right of the number (own definition) is the reason for saving the error     print  "error: you  Must input a number ",reason  except  (keyboardinterrupt, eoferror):      print  "user cancelled example three:#!/usr/bin/env pythontry:     num = 100 / int (Raw_input ("number: ")) except:                 //except: Indicates that all exceptions are caught, but this is not recommended     print  " something wrong      because I don't know what the error is.

3.2 Else Statement &&finally statement

Example 4 is a more complete catch exception and no exception after the program how to execute the example, no exception to use the Else statement execution, the last finally statement, regardless of exception will be executed, can be used after the file opened after an exception caused the file is not closed, data corruption may occur, Use finally to ensure that the file always shuts down normally.

Example four: #!/usr/bin/env pythontry:    num = 100 / int (Raw_input (" number:  "))      except  (Valueerror, zerodivisionerror),e      //different exceptions, output different information, and save the error message     print  "error:", eexcept  ( Keyboardinterrupt, eoferror):         //Two kinds of exit, all friendly tips exit      print  "Exit." else:                                          //If there is no exception, the normal output num    print numfinally:                                       // Whether or not an exception occurs, it willExecute this statement     print done 

3.3 With statements

The WITH statement is used to simplify the code by placing the open file operation in the With statement, and the file will be closed automatically when the code block ends

>>> with open ("try.py") as f: ... data = F.readlines () ...>>> with open ("/etc/passwd") as F: ... fo R line in F: ... print line,

4. Triggering an exception

(1) to throw an exception, the simplest form is to enter the keyword raise, followed by the name of the exception to be thrown

(2) When executing the Raise statement, Python creates an object of the specified exception class

(3) The Raise statement can also specify parameters to initialize the exception object

#!/usr/bin/env pythonfor i in range: if I > 10:raise valueerror, "Diaosi" Print I,[[email protected] python]# python raise1.py//Execute program is the following effect 0 1 2 3 4 5 6 7 8 9 10Traceback (most recent call last): File "raise1.py", Line 5, in <module> raise ValueError, "Diaosi" Valueerror:diaosi

5. Assertions

(1) Assertion is a sentence that must be equivalent to a Boolean-value-true decision

(2) In addition, the occurrence of an exception also means that the expression is false

>>> assert 7 > 3, "wrong"//is True, there is no output >>> assert 7 < 3, "wrong"//is False, then output, number The statement behind Traceback (most recent call last): File "<stdin>", line 1, in <module>assertionerror:wrong


This article is from the "Court of the Odd Tree" blog, please be sure to keep this source http://zhangdl.blog.51cto.com/11050780/1834195

Learn to write: Python errors, exceptions, assertions

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.