Exceptions and Errors
One: Syntax error (this error, the syntax of the Python interpreter cannot be detected, must be corrected before the program executes)
#语法错误示范一if # syntax error demonstration two DEF test: pass# syntax error demo three print (haha
Two: Logic error
#用户输入不完整 (e.g. null input) or input illegal (input not a number) num=input (">>:") int (num) #无法完成计算res1 =1/0res2=1+ ' str '
What is an exception
An exception is a signal that an error occurs while the program is running, and in Python the exception that is triggered by the error is as follows
Types of exceptions in Python
Different exceptions in Python can be identified in different types (Python unifies classes and types, types as classes), non -identical class objects identify different exceptions, 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
l=[' Egon ', ' AA ']l[3]
dic={' name ': ' Egon '}dic[' age ']
s= ' Hello ' int (s)
Common exceptions
Exception handling
After an exception occurs
The code after the exception is not executed.
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
Why do you want to do exception handling?
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, and the code behind it does not run, who will use a software that is running with a sudden crash.
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: Using the IF-judgment
Num1=input (' >>: ') #输入一个字符串试试int (NUM1)
#_ *_coding:utf-8_*___author__ = ' Linhaifeng ' num1=input (' >>: ') #输入一个字符串试试if num1.isdigit (): int (NUM1) # Our Orthodox program is here, and 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 situations, execute my logic here ') ' Question one: using the If method we only add exception handling for the first piece of code, but these if are not related to your code logic, This way your code will not be easy to read because of poor readability. Second: This is just a small logic in our code, if the logic is much like, then every time we need to judge the content, it will be inverted our code is very verbose. ‘‘‘
Summarize:
1.if-Judging exception handling can only be done for 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. Frequent writes in your program are not related to the program itself, and if it is related to exception handling, it will make your code very readable.
3.if is able to solve the anomaly, but there are problems, so do not jump to the conclusion that if can not be used for exception handling.
How you handled the exception handling before
def test (): print (' Test running ') choice_dic={ ' 1 ': test}while True: choice=input (' >>: '). Strip () if not choice or choice not in Choice_dic:continue #这便是一种异常处理机制啊 Choice_dic[choice] ()
Two: 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: When an exception is detected in try, the logic for this position is executed
f = open (' a.txt ') G = (Line.strip () for line on F) for line in G: print (line) Else: F.close ()
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 () "Next (g) will trigger an iteration F, then next (g) can read a line of the file, No matter how big the file A.txt, there is only one line of content in memory at the same time. Tip: G is based on file handle F and can only execute f.close () ' "After next (g) throws an exception stopiteration
Part2: The exception class can only be used to handle the specified exception condition and cannot be processed if a non-specified exception occurs.
# 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 As 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 use the above form directly, other exceptions can be ignored
You're right, but you should see it in two different ways.
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.
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 it means that you use the same logic to handle all exceptions (the logic here is the block of code that follows the current expect)
2. If the effect you want is that we need to customize different processing logic for different exceptions, 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)
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)
Part5: Exception of other institutions
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)
PART6: Active Triggering 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.msgtry: raise Evaexception (' type error ') except Evaexception as E: print (e)
PART8: Assertion
# assert Condition Assert 1 = = 1 assert 1 = = 2
Part9:try. Except ways to compare the benefits of the IF way
Try: 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 (Python unifies classes and types, type is a Class), and for the same exception, a except can be caught, an exception that can handle multiple pieces of code at the same time (without ' writing multiple if judgments ') reduces code and enhances readability
Use try: The way of 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;
When to use exception handling
Some students will think so, after learning the exception processing, good strong, I want to each of my procedures are added try...except, dry wool to think it will have logic error Ah, this is very good ah, multi-province brain cell = = = 2B Youth Happy Many
Try...except should be used sparingly, because it is an exception-handling logic that you attach to your program, which is not related to your main work.
This kind of thing adds more, will cause your code readability to be poor, only if some exception is unpredictable, should add try...except, other logic error should try to correct
python--Exception Handling