This article and everyone to share is mainly python3 in some of the common anomalies and related exception handling, a look at it, hope to learn from you python3 helpful.
First, what is an exception
An exception is a signal that an error occurs when the program is running (an exception occurs when the program is in error, the exception is thrown if the program does not handle it, and the program terminates), and in Python, the exception that is triggered by the error is as follows:
And the mistake is divided into two kinds
#语法错误示范一 If #语法错误示范二 def test: Pass #语法错误示范三 Class Foo Pass #语法错误示范四 Print (haha
1. Syntax error (this error, the syntax of the Python interpreter can not be detected, must be corrected before the program executes)
#TypeError: int type is not iterative For I in 3: Pass #ValueError Num=input (">>:") #输入hello int (num)
#NameError Aaa
#IndexError l=[' Hello ', ' AA '] L[3]
#KeyError dic={' name ': ' Hello '} Dic[' age ']
#AttributeError Class Foo:pass Foo.x
#ZeroDivisionError: Unable to complete calculation res1=1/0 res2=1+ ' str '
2. Logic Error
Ii. Types of anomalies
Different exceptions in Python can be identified in different types (Python unifies class and type, type as Class), an exception identifies an error
Attributeerror attempts to access a tree that does not have an object, 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 using a variable that has not been assigned to an object 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 there is another global variable with the same name. Cause you think you're accessing it ValueError Pass in a value that is not expected by the caller, even if the value is of the correct type
Common exceptions
Arithmeticerror Assertionerror Attributeerror Baseexception Buffererror Byteswarning Deprecationwarning EnvironmentError Eoferror Exception Floatingpointerror Futurewarning Generatorexit Importerror Importwarning Indentationerror Indexerror IOError Keyboardinterrupt Keyerror Lookuperror Memoryerror Nameerror Notimplementederror OSError Overflowerror Pendingdeprecationwarning Referenceerror RuntimeError Runtimewarning StandardError Stopiteration SyntaxError Syntaxwarning Systemerror Systemexit Taberror TypeError Unboundlocalerror Unicodedecodeerror Unicodeencodeerror Unicodeerror Unicodetranslateerror Unicodewarning Userwarning ValueError Warning Zerodivisionerror
More exceptions
Third, exception handling
In order to ensure the robustness and fault tolerance of the program, that is, when encountering an error, the program does not crash, we need to handle the exception,
If the condition of the error is predictable, we need to deal with if: prevention before the error occurs
age=10 While True: Age=input (' >>: '). Strip () If Age.isdigit (): #只有在age为字符串形式的整数时, the following code does not go wrong, the condition is predictable Age=int (age) if age = = Age: Print (' You Got it ') Break If the condition that the error occurs is unpredictable, you need to use try...except: processing after the error has occurred
#基本语法为 Try Blocks of code being detected Except exception type: Once an exception is detected in the try, the logic for this position is executed #举例 Try F=open (' A.txt ') G= (Line.strip () for line in F) Print (Next (g)) Print (Next (g)) Print (Next (g)) Print (Next (g)) Print (Next (g)) Except stopiteration: F.close ()
#1 Exception class can only be used to handle the specified exception condition, and cannot be handled if a non-specified exception occurs. S1 = ' Hello ' Try Int (S1) Except Indexerror as E: # uncaught exception, program direct error Print E
#2 Multi-Branch S1 = ' Hello ' Try Int (S1) Except Indexerror as E: Print (e) Except Keyerror as E: Print (e) Except ValueError as E: Print (e)
#3 Universal Anomaly exception S1 = ' Hello ' Try Int (S1) Except Exception as E: Print (e)
#4 Multi-branch anomaly and universal anomaly #4.1 If the effect you want is, no matter what happens, we discard uniformly, or use the same piece of code logic to deal with them, then the year, bold to do it, only one exception is enough. #4.2 If the effect you want is that we need to customize different processing logic for different exceptions, we need to use multiple branches.
#5 can also be a exception in multiple branches later 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)
Other bodies that #6 anomalies 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 (' Execute the module, usually for cleanup work ', whether it is abnormal or not)
#7 proactively triggering exceptions Try Raise TypeError (' type error ') Except Exception as E: Print (e)
#8 Custom Exceptions Class Egonexception (baseexception): def __init__ (self,msg): Self.msg=msg def __str__ (self): Return self.msg
Try Raise Egonexception (' type error ') Except Egonexception as E: Print (e)
#9 Assertion: Assert condition Assert 1 = = 1 Assert 1 = = 2
#10 Summary Try: Except
1: Separate the error handling from the real work 2: Code easier to organize, clearer, complex tasks easier to implement; 3: No doubt, more secure, not due to some small negligence to make the program accidentally collapsed;
View Code
Source: Network |