Abnormal handling of Python3

Source: Internet
Author: User

I. Errors and exceptions 1. Error

Syntax or logic errors before code is run

    • Syntax error (this error, the syntax of the Python interpreter cannot be detected, it must be corrected before the program executes)
    def test:            ^syntaxerror:invalid syntax
Other syntax errors

    • Logic error
#用户输入不完整 (e.g. null input) or illegal input (input not a number)

Num=input (">>:")
int (num)

Output

>>: Fsftraceback (most recent):  File '/users/hexin/pycharmprojects/py3/day9/1.py ', line 4, < module>    int (num) valueerror:invalid literal for int () with base: ' FSF '

2. Exception definitions

A problem occurred during program execution that prevented the program from executing

    • Classification of exceptions:
    1. The program encountered a logical or algorithmic error

    2. Computer error during Operation: Insufficient memory or IO error

    • Exception steps:
    1. An exception is generated, an error is checked and the interpreter considers it to be an exception, throwing an exception

    2. Exception handling, exception handling, intercepting exceptions, system ignoring or terminating program handling exceptions

3. Common exceptions
Attributeerror attempts to access properties that an object does not have, such as foo.x, but Foo has no attribute x
IOError input/output exception; Basically, the file cannot be opened
Importerror cannot introduce modules or packages; it is basically a path problem or a name error
Indentationerror syntax error (subclass); Code not aligned correctly
Indexerror Subscript index is out of sequence boundary, for example, when X has only three elements, but tries to access X[5]
Keyerror attempts to access keys that do not exist in the dictionary
Keyboardinterrupt CTRL + C is pressed
Nameerror attempt to access a variable that is not declared
SyntaxError python code is illegal, code can not compile (personally think this is a syntax error, write wrong)
TypeError incoming object types are not compliant with the requirements
Unboundlocalerror attempts to access a local variable that has not yet been set, basically because another global variable with the same name causes you to think that you are accessing it
ValueError Pass in a value that is not expected by the caller, even if the value is of the correct type

Add:

Exception Name Description Baseexception base class for all exceptions Systemexit interpreter request exit Keyboardinterrupt user interrupt Execution (usually input ^c) Exception General error Stopiterati The on iterator has no more values Generatorexit Generator (Generator) exception to notify the base class that exits all of the built-in standard exceptions StandardError arithmeticerror all numeric calculation errors for the base class floating     Pointerror floating-point calculation error Overflowerror numeric operation exceeds maximum limit zerodivisionerror except (or modulo) 0 (all data types) Assertionerror Assertion statement Failure attributeerror The object does not have this property eoferror has no built-in input, a base class that reaches the EOF tag EnvironmentError operating system error IOERROR input/output operation failed OSError operating system error WINDOWSERROR system System call failed Importerror Import Module/object failed lookuperror Invalid data query base class Indexerror sequence without this index in Keyerror map no this key memoryerror memory overflow error Error (not fatal for Python interpreter) Nameerror undeclared/initialized object (no attribute) unboundlocalerror Access uninitialized local variable referenceerror weak reference (Weak reference) attempted to access     Objects that have been garbage collected runtimeerror general run-time errors Notimplementederror not implemented methods SyntaxError Python syntax errors indentationerror indentation Errors Taberror Tab and Space mixed Systemerror General interpreter system error TypeError Invalid type operation valueerror incoming invalid parameter unicodeerror Unicode related error Unicodedecode Error Unicode decoding errors UNicodeencodeerror Unicode encoding error unicodetranslateerror Unicode conversion error warning warning base class deprecationwarning warnings about deprecated features F Uturewarning warning about constructing future semantics overflowwarning old warning about auto-promotion to long, pendingdeprecationwarning warning about attributes will be discarded Runtimewar Ning suspicious runtime behavior (runtime behavior) warning syntaxwarning suspicious syntax warnings userwarning user code generated warnings

Ii. exception handling 1. Definition of exception handling

The Python interpreter detects an error, triggering an exception (also allowing the programmer to trigger an exception himself)

Programmers write specific code that is specifically designed to catch this exception (this code is independent of the program logic and is related to exception handling)

If the capture succeeds, go to another processing branch, execute the logic you've customized for it, and the program won't crash, which is exception handling

2. Meaning of exception handling

The Python parser executes the program, detects an error, triggers an exception, the exception is triggered and is not processed, the program terminates at the current exception, and the subsequent code does not run, so you must provide an exception handling mechanism to enhance the robustness and fault tolerance of your program.

3. How to perform exception handling
    • Using the IF-judgement
Num1=input (' >>: ') #输入一个字符串试试if num1.isdigit ():    int (NUM1) #我们的正统程序放到了这里, the rest belongs to the exception handling category Elif Num1.isspace ():    print (' input is a space, execute my logic here ') Elif len (num1) = = 0:    print (' Input is empty, execute my logic here ') Else:    print (' Other situation, execute my logic here ') # The second segment of code # Num2=input (' >>: ') #输入一个字符串试试 # int (num2) #第三段代码 # num3=input (' >>: ') #输入一个字符串试试 # int (num3)


Question one:
Using the If method we only add exception handling for the first piece of code, and for the second piece of code you have to re-write a bunch of if,elif and so on.
And these if, with your code logic is not related to the poor readability

Question two:
The first code and the second piece of code are actually the same exception, all valueerror, the same error is supposed to be handled only once, and if, because of the conditions of the two if, this can only force you to re-write a new if to deal with the exception of the second section of the code
The third paragraph is the same.

    • Try...except

Grammar:

try:< Statement >        #运行别的代码except < exception type >:< statement >        #如果在try部份引发了 ' name ' exception except < exception type > as < data > :< Statement >        #如果引发了 ' name ' exception, get additional data else:< statement >        #如果没有异常发生

Note:

Python2 and 3 deal with the syntax of the EXCEPT clause is a little different, need attention;

Python2

Try:    print (1/0) except Zerodivisionerror, err: #, plus reason parameter name     print (' Exception: ', err)

Python3

Try:    print (1/0) except Zerodivisionerror as err:        # as plus reason parameter name    print (' Exception: ', err)

Cases

Try:    fh = open ("Testfile", "W")    Fh.write ("This is a test file for testing exceptions!") Except IOError:    print ("Error: Failed to find file or read file") Else:    print ("content written to file succeeded")    Fh.close ()

Output

Content written to file succeeded

Note:

The exception class can only be used to handle the specified exception condition, and cannot be processed if a non-specified exception occurs. ( exceptions are caused by program errors, syntax errors are not related to exception handling and must be fixed before the program is run)

# uncaught exception, program direct error S1 = ' Hello ' try:    int (s1) except Indexerror as E:    print E

Output

  File "/users/hexin/pycharmprojects/py3/day9/1.py", line one    print e          ^syntaxerror:missing parentheses in call To ' print '

    • Multi-Branch
Try:    msg=input (' >>: ')    int (msg) #ValueError    #    # print (x) #NameError # # # # #    l=[1,2] # #    l[10] #IndexError    # #    1+ ' asdfsadfasdf ' #TypeErrorexcept valueerror as E:    print (e) except Nameerror:    print (' Nameerror ') except Keyerror as E:    print (e)
>>:gginvalid literal for int. () with base: ' GG '

    • Universal anomaly

In Python exceptions, there is a universal exception: Exception, he can catch arbitrary exceptions

S1 = ' Hello ' try:    int (s1) except Exception as E:    ' discard or perform other logic '    print (e)

Output

Invalid literal for int. () with base: ' Hello '

    • try-finally statements

The try-finally statement executes the final code regardless of whether an exception occurs.

S1 = ' Hello ' try:    int (s1) except Indexerror as E:    print (e) except Keyerror as E:    print (e) except ValueError as E:    print (e) #except Exception as e:#    print (e) Else:    print (' Execute me without exception in ' Try code block ') Finally:    print (' No matter if it's abnormal or not, Will execute the module, usually for cleanup work)

Output

Invalid literal for int () with base: ' Hello ' whether it's unusual or not, it will execute the module, usually for cleanup work

    • Raise active triggering exception

We can use the raise statement to trigger the exception ourselves

The raise syntax format is as follows:

raise [Exception [, Args [, Traceback]]

The type of exception in the statement is an exception (for example, the Nameerror) parameter is an exception parameter value. This parameter is optional and if not provided, the exception parameter is "None".

The last parameter is optional (rarely used in practice) and, if present, is the tracking exception object.

Try:    raise TypeError (' type error ') except Exception as E:    print (e)

Output

Type error

    • Custom exceptions
Class Hexinexception (baseexception):    def __init__ (self,msg):        self.msg=msg    def __str__ (self):        Return Self.msgtry:    raise Hexinexception (' type error ') except Hexinexception as E:    print (e)

Output

Type error

Abnormal handling of python3 (RPM)

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.