What ' s the anomaly
There is an exception in the Python program, which is the bug. If the exception program error, the code after the exception will not continue to execute, this is a normal program is not allowed to appear, but in some programs to interact with the user input problems inevitably caused by the exception, At this point we are going to add exception-handling code to the program to prevent our program from crashing because of an exception.
Exceptions are errors, two types of errors, one for syntax errors and one for logic errors.
syntax error: the programmer in writing code because the error caused by improper operation, the resulting exception is quite low, the way to deal with the exception is artificial manual correction. When writing a program, we must be careful to note that grammatical errors are very low-level behavior, can be avoided, make this mistake will only be your workload increased, the increase in class time
logic Error: An exception that is caused by a user entering an incomplete or incorrect input data type in a program interaction, or causing an exception due to a different data type that needs to be computed for some reason, etc.
# 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'
In Python, different types of exceptions can be identified in different types (Python unifies classes and types, types as classes), different class objects identify different exceptions, and an exception identifies an error.
For example: Index exception--indexerror, keyword exception--keyerror, value exception--valueerror, etc.
Common exceptions are listed below:
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
More Exceptions:
Arithmeticerrorassertionerrorattributeerrorbaseexceptionbuffererrorbyteswarningdeprecationwarningenvironmenterroreoferror Exceptionfloatingpointerrorfuturewarninggeneratorexitimporterrorimportwarningindentationerrorindexerrorioerrorkeyboardint Erruptkeyerrorlookuperrormemoryerrornameerrornotimplementederroroserroroverflowerrorpendingdeprecationwarningreferenceerr Orruntimeerrorruntimewarningstandarderrorstopiterationsyntaxerrorsyntaxwarningsystemerrorsystemexittaberrortypeerrorunbou Ndlocalerrorunicodedecodeerrorunicodeencodeerrorunicodeerrorunicodetranslateerrorunicodewarninguserwarningvalueerrorwarni Ngzerodivisionerror
more Exceptions
Exception Handling
The Python interpreter detects an error, triggering an exception (which also allows 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, it goes to another processing branch, executes the logic specifically tailored to it, and the program does not crash, which is exception handling
Exception handling is a mechanism to enhance the robustness and fault tolerance of a program
Well, let's learn how to do exception handling.
We used to avoid exceptions in the form of if conditions, such as:
#_*_coding:utf-8_*_NUM1=input ('>>:') ifnum1.isdigit (): Int (NUM1)#Our Orthodox program is here, and the rest belongs to the exception-handling category .elifnum1.isspace ():Print('you entered a space, please enter a number type')elifLen (num1) = =0:Print('you entered a blank, please enter a number type')Else: Print('for other situations, please enter a number type')" "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.
As we can see, there are several problems that can be dealt with if the exception is handled by using if:
Problem one: If the exception handling of the judgment can only be for a certain piece of code, for different pieces of the same type of error you need to write a duplicate if to handle.
Problem two: Frequent writing in the program is independent of the program itself, and if the exception is handled, the readability of the code becomes worse
So although if can be used to handle exceptions, it makes code redundant. Here, Python provides a special way of handling exceptions-try
Try : instrumented code block except exception type: When an exception is detected in a try, the logic for this position is executed
Here are some examples:
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 ()" "
The exception class can only be used to handle the specified exception condition, and if the program produces an exception that is not the exception specified by the exception class, an error is made. So, we can do multiple branching of exception handling, and finally use a Universal exception handler class exception to handle unexpected exceptions.
S1 ='Hello'Try: Int (s1)exceptIndexerror as E:#Index exception when executed here Print(e)exceptKeyerror as E:#keyword exception when executed here Print(e)exceptValueError as E:#The value is abnormal when executed here Print(e)exceptException as E:#Universal exception, if there is a different exception to the above specified exception, go here Print(e)
The universal exception is really omnipotent, he can handle all the exceptions, but not that you usually use it when you encounter an exception, then nothing else. When you use it, you need to divide the situation:
1. If the effect we want is that no matter what happens, we discard them uniformly, or use the same piece of code logic to handle them, then only one exception is enough.
2. If the effect we want is that we need to customize different processing logic for different exceptions, we need to use multiple branches. We can add a exception at the end of the multi-branch to prevent the program from crashing after an unexpected exception has occurred.
Exception handling can also be used in the else, and finally, in fact, these two dispensable, not to say that the non-use is not
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')
Custom Exceptions
Sometimes programmers can throw an exception themselves, or they can customize the exception
#proactively triggering exceptionsTry: RaiseTypeError ('Type Error')exceptException as E:Print(e)#Custom ExceptionsclassEgonexception (baseexception):#custom exceptions must inherit Baseexception def __init__(self,msg): Self.msg=msgdef __str__(self):returnself.msgTry: RaiseEvaexception ('Type Error')exceptevaexception as E:Print(e)
Word
Try: Except this exception handling mechanism is to replace if that way, so that the program without sacrificing readability of the premise of enhancing robustness and fault tolerance.
Exception types are customized for each exception, and for the same exception, a except can be captured to handle multiple code exceptions (without ' writing multiple if judgments ') to reduce code and enhance readability
Use try: Advantages of the except approach
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;
But!!! Try...except should be used sparingly, because it is an exception-handling logic attached to your program, which is not related to the main work, which adds more, or causes code readability to become worse. Therefore, only if some exceptions can not be avoided, should be added try...except, other logic errors should be as far as possible to correct.
What ' s the python exception handling