I. what is abnormal?
An exception is a signal that something is wrong when the program is running (an exception is generated when the program is wrong, and if the program is not handling it, the exception is thrown, and the program runs with it)
And mistakes fall into two categories.


#TypeError:intType is not iterative. for i in 3: pass #ValueError num=input(">>: ") #Input hello int(num) #NameError aaa #IndexError l=['egon','aa'] l[3] #KeyError dic={'name':'egon'} dic['age'] #AttributeError class Foo:pass Foo.x #ZeroDivisionError:Unable to complete calculation res1=1/0 res2=1+'str'
2.Logical error
Two. Common anomalies
AttributeError Trying to access a tree with no object, such as foo.x, but foo has no attribute xIOError input/Output exception; basically unable to open file.ImportError cannot import modules or packages; basically, it is a path problem or a name error.IndentationError syntax error (subclass); code is not aligned correctly.Under IndexErrorThe index index exceeds the sequence boundary, for example, when x has only three elements, it tries to access x[.5] KeyError Trying to access keys that do not exist in the dictionaryKeyboardInterrupt Ctrl+CBe pressedNameError uses a variable that is not yet assigned to an object.SyntaxError Python code is illegal, and the code can not be compiled.The type of TypeError incoming object is not consistent with the requirement.UNboundLocalError attempts to access an unset local variable, essentially because there is another global variable with the same name.Which leads you to think that it is visiting it.ValueError passes a caller's undesired value even if the type of the value is correct.
Three. Exception handling
In order to ensure the robustness and fault tolerance of the program, that is, the program will not crash when encountering errors, we need to handle exceptions.
If the conditions under which errors occur are predictable, we need to handle them with if: prevent them before they occur
AGE=10 while True: age=input('>>: ').strip() if age.isdigit(): #Only when age is an integer in string form, the following code will not go wrong. The condition is predictable. age=int(age) if age == AGE: print('you got it') break
If the conditions under which the error occurs are unpredictable, try… Except: Handle after the error occurs
#The basic syntax is try: Code blocks detectedexcept Exception type:Once an exception is detected in try, the logic of the location is executed.#Give an example 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()
Exception handling:
#1 Exception classes can only be used to handle specified exceptions. If no exception is specified, it can not be processed. s1 = 'hello' try: int(s1) except IndexError as e: # The exception was not captured, and the program was directly reported. 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 exception Exception s1 = 'hello' try: int(s1) except Exception as e: print(e) #4 Multiple branch anomalies and omnipotent anomalies #4.1 If the effect you want is that no matter what happens, we discard them all together, or use the same piece of code logic to handle them, then Sao Nian, do it boldly, just one Exception is enough. #4.2 If you want the effect that we need to customize different processing logic for different exceptions, you need to use multiple branching. #5 It can also be multiple branches later on a Exception. 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) #6 Other institutions of exception 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('tryIf I have no exception in the code block, execute me.') finally: print('Whether abnormal or not, the module will be executed, usually cleaning.') #7 Active trigger exception try: raise TypeError('error in type') except Exception as e: print(e) #8 Custom exception class EgonException(BaseException): def __init__(self,msg): self.msg=msg def __str__(self): return self.msg try: raise EgonException('error in type') except EgonException as e: print(e) #9 Assertion: assert condition assert 1 == 1 assert 1 == 2 #10 Sum up try..Except 1:Separate the error handling from the real work.2:Code is more organized, clearer, and complex tasks are easier to achieve.3:There is no doubt that it is safer, so that the procedure will not crash due to minor negligence.