- An error and an exception
- Two exception handling
- 2.1 What is exception handling?
- 2.2 Why do I have to do exception handling?
- 2.3 How do I do exception handling?
- Three when to use exception handling
Exceptions and ErrorsPart1: Errors are unavoidable in the program, and errors are divided into two
1. Syntax error (this error, the syntax of the Python interpreter can not be detected, must be corrected before the program executes)
#语法错误示范一if # syntax error demonstration two DEF test: pass# syntax error demo three print (haha
2. Logic error (logic error)
# The user input is incomplete (for example, the input is empty) or the input is illegal (input is not a number)Num=input ("") int (num)# Unable to complete calculation 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 by different types, different class objects identify different exceptions, and an exception identifies an error
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
Common Exceptions
Arithmeticerrorassertionerrorattributeerrorbaseexceptionbuffererrorbyteswarningdeprecationwarningenvironmenterroreoferror Exceptionfloatingpointerrorfuturewarninggeneratorexitimporterrorimportwarningindentationerrorindexerrorioerrorkeyboardint Erruptkeyerrorlookuperrormemoryerrornameerrornotimplementederroroserroroverflowerrorpendingdeprecationwarningreferenceerr Orruntimeerrorruntimewarningstandarderrorstopiterationsyntaxerrorsyntaxwarningsystemerrorsystemexittaberrortypeerrorunbou Ndlocalerrorunicodedecodeerrorunicodeencodeerrorunicodeerrorunicodetranslateerrorunicodewarninguserwarningvalueerrorwarni Ngzerodivisionerror
more Exceptions
Exception handling
what is an exception?
After an exception occurs
The code after the exception is not executed.
What is exception handling:
The Python interpreter detected an error, triggering an exception (also allowing the programmer to trigger the 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 ("# Enter a string to try Int (NUM1)
#_*_coding:utf-8_*___author__='Linhaifeng'NUM1=input ('>>:')#Enter a string to tryifnum1.isdigit (): Int (NUM1)#Our Orthodox program is here, and the rest belongs to the exception-handling category .elifnum1.isspace ():Print('Enter a space and execute my logic here.')elifLen (num1) = =0:Print('the input is empty, just execute my logic here.')Else: Print('other situations, execute my logic here.')" "Problem One: We only add exception handling for the first piece of code by using if, 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 these things, we'll invert our code to be very verbose. " "
using if for exception handling
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.
What's important here is that Python customizes a type for each exception, and then provides a specific syntax structure for exception handling
Basic Syntax 1:
Try : instrumented code block except exception type: When an exception is detected in a try, the logic for this position is executed
Try: 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 ()" "Next (g) triggers the iteration F, followed by Next (g) to read a line of the file, no matter how large the file A.txt, and only one line of content in memory at the same time. Tip: G is based on the file handle F and therefore can only be executed after next (g) throws an exception stopiteration () F.close ()
Example
Art2: The exception class can only be used to handle the specified exception condition and cannot be processed if a non-specified exception occurs.
# exception not caught, program directly error 'hello'try: int (s1)except Indexerror as E : print E
Part: Multi-branch
' 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:
' 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.
' Hello ' Try : int (s1)except exception,e: ' discard or perform other logic ' Print(e)# If you unify with exception, yes, you can catch all the anomalies, 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)
' 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)
Multi-branch +exception
Part5: Exception of other institutions
S1 ='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')
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): Span style= "COLOR: #0000ff" >return self.msg try : raise Evaexception ( " type error " ) except Evaexception as E: print (E)
PART8: Assertion
# Assert Condition assert 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;
Back to the top 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