what is an exception
The so-called exception is the error signal that occurs when the program is running, and an exception is generated when a program error occurs. If the program does not handle it, an exception is thrown and the program terminates.
The following is an example of an exception being generated:
It said that the program error will produce an exception, and the error is divided into two kinds:
# syntax error demonstration one if # syntax error demonstration two def Test: Pass # syntax error model three class Foo Pass # syntax error demonstration four Print (haha# This error, the syntax of the Python interpreter cannot be detected, must be corrected before the program executes
syntax error
#Typeerror:int type non-iterative forIinch3: Pass#ValueErrorNum=input (">>:")#Enter Helloint (num)#NameerrorAAA#Indexerrorl=[' One','AA']l[3]#Keyerrordic={'name':'Lao Wang'}dic[' Age']#AttributeerrorclassFoo:Passfoo.x#Zerodivisionerror: Unable to complete calculationres1=1/0res2=1+'Str'
Logic ErrorCommon Exceptions
Attributeerror attempts to access a tree that does not have an object, such as foo.x, but Foo does not have a property xioerror input / output exception; it is basically impossible to open the file Importerror the module or package cannot be introduced is basically a path problem or name error Indentationerror syntax error (subclass); The code is not aligned correctly indexerror the subscript index exceeds the sequence boundary, for example, when X has only three elements, it attempts to access x[5]keyerror Attempting to access a key that does not exist in the dictionary keyboardinterrupt Ctrl+c is pressed nameerror use a variable that has not been assigned to the object SyntaxError Python code is illegal, the code cannot compile (personally think this is a syntax error, Wrong) TypeError the incoming object type is not compliant with the requirements Unboundlocalerror attempts to access a local variable that is not yet set, basically because another global variable with the same name causes you to think that you are accessing it valueerror a value that the caller does not expect , even if the type of the value is correct
The exceptions are not listed, only a few common ones are written, and the reasons for their possible causes.
Exception Handling
A misunderstanding
The thought of anomalies, many people only think of try...except, this is not true.
If the condition of the error is predictable, we can use if to process it and prevent it before the error occurs.
age=10 while True: The Age =input ("). Strip () if # The following code will not be faulted unless the age is an integer in the form of a string, which is a predictable age=Int ( age)if Age = = Age : print('yougot it') break
View Code
If the condition that the error occurs is unpredictable, you need to use try...except to process it after the error has occurred.
#the basic syntax isTry: instrumented block of codeexceptException Type: When an exception is detected in try, the logic for this position is executed#ExampleTry: F=open ('a.txt') G= (Line.strip () forLineinchf)Print(Next (g))Print(Next (g))Print(Next (g))Print(Next (g))Print(Next (g))exceptstopiteration:f.close ()
View Code
What you need to know about exception handling:
#The 1 Exception class can only be used to handle the specified exception condition, and cannot be processed if a non-specified exception occurs. S1 ='Hello'Try: Int (s1)exceptIndexerror as E:#exception not caught, program directly error Printe#2 Multi-branchS1 ='Hello'Try: Int (s1)exceptIndexerror as E:Print(e)exceptKeyerror as E:Print(e)exceptValueError as E:Print(e)#30,000 can abnormal exceptionS1 ='Hello'Try: Int (s1)exceptException as E:Print(e)#4 Multi-branch anomaly and universal Anomaly#4.1 If you want the effect is, regardless of 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 in multiple branches later a exceptionS1 ='Hello'Try: Int (s1)exceptIndexerror as E:Print(e)exceptKeyerror as E:Print(e)exceptValueError as E:Print(e)exceptException as E:Print(e)#6 Exceptions for other agenciesS1 ='Hello'Try: Int (s1)exceptIndexerror as E:Print(e)exceptKeyerror as E:Print(e)exceptValueError as E:Print(e)#except Exception as E:#print (e)Else: Print('execute My code block without exception in try')finally: Print('The module is executed whether it is unusual or not, usually for cleanup work')#7 Active Trigger ExceptionTry: RaiseTypeError ('Type Error')exceptException as E:Print(e)#8 Custom Exceptionsclassegonexception (baseexception):def __init__(self,msg): Self.msg=msgdef __str__(self):returnself.msgTry: RaiseEgonexception ('Type Error')exceptegonexception as E:Print(e)#9 Assertion: Assert conditionassert1 = = 1assert1 = = 2#10 Summary Try: Except1: Separating error handling from real work2: Code is easier to organize, clearer, and complex tasks are easier to implement;3: No doubt, more secure, not due to some small negligence to make the program accidentally collapsed;
Exceptions in Python