Exception handling 1. Exceptions and Errors Part1: Errors are unavoidable in the program, and errors are divided into two 1) syntax errors (this error, the parser can not get through the syntax detection, must be corrected before the program execution) 2) Logic error (logic error) Part2: Exception is a signal that an error occurs while the program is running Exception classes in Part3:python in Python different exceptions can be identified with different types (Python unifies class and Class class type, type as Class), different class objects identify different objects, and an exception identifies an error. Common 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 the 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 More Exceptions: arithmeticerrorassertionerrorattributeerrorbaseexceptionbuffererrorbyteswarningdeprecationwarningenvironmenterroreof Errorexceptionfloatingpointerrorfuturewarninggeneratorexitimporterrorimportwarningindentationerrorindexerrorioerrorkeyboa Rdinterruptkeyerrorlookuperrormemoryerrornameerrornotimplementederroroserroroverflowerrorpendingdeprecationwarningreferen CeerroRruntimeerrorruntimewarningstandarderrorstopiterationsyntaxerrorsyntaxwarningsystemerrorsystemexittaberrortypeerrorunboun Dlocalerrorunicodedecodeerrorunicodeencodeerrorunicodeerrorunicodetranslateerrorunicodewarninguserwarningvalueerrorwarnin Gzerodivisionerror what is an exception? A: After the exception occurs, the code after the exception is not executed. What is exception handling? A: The Python interpreter detects an error, triggers an exception (and also allows the programmer to trigger the exception itself) the programmer writes specific code specifically to catch the exception (this code is independent of the program logic and is related to exception handling) if the capture succeeds, it enters another processing branch, executes your custom-made logic, Program does not crash, this is exception handling. Why do you want to do exception handling? A: The python parser goes to execute the program, detects an error, triggers an exception, the exception is triggered and is not processed, the program terminates at the current exception, the following code will not run, who will be running a sudden crash software. So you have to provide an exception handling mechanism to enhance the robustness and fault tolerance of your program. How do I do exception handling? First of all, the exception is caused by a program error, grammatical errors are not related to exception handling, must be corrected before the program runs. One: Use if to determine 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, just execute my logic here ') Else:print (' Other situation, execute my logic here ') ' Question one: use I F We only add exception handling for the first piece of code, but these if are not related to your code logic, so your code will not be easy to read because of poor readability. This is just a small logic in our code, and if there is a lot of logic like that, then every time we need to judge the content, will be inverted our code is particularly verbose. "Summary: 1.if-Judging exception handling onlyFor a piece of code, for the same type of error for different pieces of code you need to write the duplicate if to handle it. 2. In your program frequently write not related to the program itself, and the exception to deal with the IF, will make your code readability is extremely poor 3.if is able to solve the exception, but there are problems, so, do not jump to the conclusion that if can not be used for exception handling. def test (): Print (' Test running ') choice_dic={' 1 ': Test}while true:choice=input (' >>: '). Strip () if not C Hoice or choice not in Choice_dic:continue #这便是一种异常处理机制啊 Choice_dic[choice] () II: Python customizes a type for each exception, and then provides a specific syntax structure for Exception handling Part1: Basic syntax try: code block except exception type: The logical example of executing this position when an exception is detected in a try: F = open (' a.txt ') G = (Line.strip () for lines in f) G:print (line) else:f.close () Read File example 1 try:f = open (' a.txt ') G = (Line.strip () for line in F) Print (Next (g)) print (Next (g)) print (Next (g)) print (Next (g)) except Stopiteration:f.close () ' "Next (g) will trigger an iteration F, and next (g) will be able to read a line of the file, no matter how large the file A.txt, the same time there is only one line of content in memory. Tip: G is based on the file handle F, so only after next (g) throws an exception stopiteration can execute F.close () "Read File Example 2 Part2: The exception class can only be used to handle the specified exception condition, if the non-specified exception is not processed. # uncaught exception, program direct error S1 = ' Hello ' try:int (S1) except Indexerror as E:print (e) PART3: Multi-branch S1 = ' Hello ' try:int (S1) except Indexerror as E:print (e) except Keyerror as E:print (e) except valueerror a S E:print (e) PART4: Universal exception in Python's exception, there is a universal exception: Exception, he can catch arbitrary exceptions, namely: S1 = ' Hello ' try:int (S1) except Exception as E: Print (e) You may say that since there is a universal exception, then I directly use the form above, and other exceptions can be ignored you are right, but should be divided into two situations to see 1. If the effect you want is, no matter what happens, we discard them uniformly, or use the same piece of code logic to handle them, So sexy years, bold to do it, only a exception is enough. S1 = ' Hello ' try:int (S1) except exception,e: ' Discard or perform other logic ' print (e) #如果你统一用Exception, yes, it is possible to catch all exceptions, but that means you use the same when handling all exceptions A logic to deal with (the logic here is the current expect following code block) 2. If the effect you want is that we need to customize different processing logic for different exceptions, then we need to use multiple branches S1 = ' Hello ' try:int (S1) except Indexerror as E:print (e) except Keyerror as E:print (e) except ValueError as E:print (e) 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) except EXC Eption as E:print (e) Multi-branch +exception PART5: Exception of other institutions S1 = ' Hello ' try:int (S1) except Indexerror as E:print (e) except Keyerror asE:print (e) except ValueError as E:print (e) #except Exception as e:# print (e) else:print (' Try to execute me in code block without exception ') FINA Lly:print (' Execute the module, usually for cleanup ') Part6: An active trigger exception try:raise TypeError (' type error ') except Exception as E:print (e) PART7: Custom Exception class Evaexception (baseexception): def __init__ (self,msg): Self.msg=msg def __str__ (self): return self.msg try:raise evaexception (' type error ') except Evaexception as E:print (e) Part8: Assert # Assert condition (is a bool value) Returns true to continue execution, false throws exception assert 1 = = 1 assert 1 = = 2 Part9:try. Except the way to compare if the benefits of RY. Except this exception handling mechanism is to replace if that way, allowing your program to enhance robustness and fault tolerance without sacrificing readability. Exception types are customized for each exception (in Python, the class and type are uniform, the type is the Class), and for the same exception, A except can capture an exception that can handle multiple pieces of code at the same time (without ' writing multiple if judgments ') to reduce the code and enhance readability using try. Except Way 1: separating error handling from real work 2: The code is easier to organize, clearer, and complex tasks are more easily implemented; 3: No doubt, more secure, not because of some small negligence to make the program accidentally collapsed; When do you use exception handling? A: Ry...except should try to use less, because it is you attach to your program of an exception handling logic, and our main work is not related to this kind of thing add more, will lead to your code readability is poor, only in some unexpected circumstances, should be added try ... Except, other logic errors should be corrected as much as possible.
Python Exception handling