Write it at the front
What is an anomaly ?
How to handle exceptions ?
try And except
usage
Example
python Standard exception
At the end
Write it at the fronttoday Python The content of the notes is :
exception handling
once Python An exception occurred in the script , The program needs to catch and handle exceptions .
Exception handling enables the program to continue normal execution after handling exceptions , So as not to crash or terminate the execution .
What is an anomaly ?When Python An exception occurs when the program cannot be processed properly . Exception is Python object , A mistake .
When Python We need to catch and deal with the exception of the script , Otherwise, the program will terminate
for instance :
>>> a = int(input())xTraceback (most recent call last): File "<stdin>", line 1, in <module>ValueError: invalid literal for int() with base 10: 'x'
In the above code ,ValueError Is an exception , By exception information , We can find the wrong line number .
How to handle exceptions ?In the previous example , The revised code is :
>>> while True:try:a = int(input(" Please enter an integer :"))print(" The number you entered is :",a)breakexcept ValueError:print(" You are not entering an integer !") Please enter an integer :3.14 You are not entering an integer ! Please enter an integer :a You are not entering an integer ! Please enter an integer :6 The number you entered is : 6
In the above procedure :
ad locum , There are two new keywords :try and except;
I talked about it before. , When the value we enter is not an integer ,int() The function will throw ValueError abnormal ;
be try Detected in block ValueError When abnormal , It will end try Block subsequent code ;
Turn to execution except Block code ;
When except ValueError: After the code is executed , The program will continue from while The beginning of the statement continues ;
It should be noted that , As long as the input is not an integer ,int() Functions will throw ValueError abnormal , that try: After break Statement will not execute , The program will cycle all the time ;
Last , When the input value is an integer ,int() Function will not throw ValueError abnormal ,try Block can continue to execute , Until I met break sentence , The program will exit the loop ;
try And excepttry And except Statement is used to detect try Exception in statement block , And let except Statement to catch and handle exceptions ;
usage If you don't want the program to be forced to end after an exception occurs , It needs to be in try Sentence block
Exception caught in , And in except Sentence block
Exception handling in .
try
And except
Can be used as follows :
The analysis is as follows :
Exampletry Statement blocks in execute first .
If try An exception occurred during the execution of a statement in the statement block ,Python Just jump to except part , From top to bottom, judge whether the exception object thrown is related to except The following exception classes match , And execute the first... That matches the exception except Statement block after , Exception handling completed .
If something goes wrong , But no matching exception category was found , Execute... Without any matching type except Statement block after statement , Exception handling completed .
If try An exception occurred in one of the statements in the statement block , There is no match except Clause , There is no one without a matching type except part , The exception will be submitted to the upper layer try/except Statement for exception handling , Or until the exception is passed to the top layer of the program , This ends the program .
If try No exception occurs when any statement in the statement block is executed ,Python Will perform else Statement block after statement .
After execution except After the exception handling statement or else After the following statement block , The program must execute finally Statement block after . The statement block here is mainly used for closing operations , Whether or not an exception occurs, it will be executed .
An exception handling module has at least one try And a except Sentence block ,else and finally Statement blocks are optional .
Look at a piece of code :
The three tests are as follows :
1) Enter... In the correct format , be except
None of the following modules will execute ,else
The resulting module will be executed ,finally
The following module statements will execute .
2) If b The value of is assigned as 0
, Will be detected ZeroDivisionError Exception object
, stay except ZeroDivisionError:
Later modules will be executed to handle the exception . After exception handling , perform finally
Statement block after .
3) If you just type a
Value ,b
No assignment , be try
The module will throw TypeError abnormal
. In program exception handling except
The handler module for this type of exception is not listed in , Without exception type except
The module can intercept the exception and handle it . After exception handling ,finally
The following statements will also be executed .
BaseException
The base class for all exceptions SystemExit
The interpreter requests exit KeyboardInterrupt
User interrupt execution ( Usually the input ^C)GeneratorExit
generator (generator) An exception occurs to notify the exit Exception
Regular error base class StopIteration
Iterators have no more values StandardError
All built-in standard exception base classes ArithmeticError
Base class for all numerical errors FloatingPointError
Floating point error OverflowError
The numerical operation exceeds the maximum limit ZeroDivisionError
except ( Or modulus ) zero ( All data types )AssertionError
Assertion statement failed AttributeError
Object does not have this property EOFError
No built-in input , arrive EOF Mark EnvironmentError
Base class for operating system errors IOError
Input / Output operation failed OSError
Operating system error WindowsError
System call failed ImportError
The import module / Object failed LookupError
Base class for invalid data query IndexError
There is no index in the sequence (index)KeyError
There is no key in the map MemoryError
Memory overflow error ( about Python The interpreter is not fatal )NameError
Not a statement / Initialize object ( There is no attribute )UnboundLocalError
Accessing an uninitialized local variable ReferenceError
Weak reference (Weak reference) Trying to access a garbage collected object RuntimeError
General runtime errors NotImplementedError
A method that has not yet been implemented SyntaxError
Python Grammar mistakes IndentationError
The indentation error TabError
Tab Mixed with Spaces SystemError
General interpreter system error TypeError
Invalid operation on type ValueError
Invalid parameter passed in UnicodeError
Unicode Related errors UnicodeDecodeError
Unicode Error in decoding UnicodeEncodeError
Unicode Error in coding UnicodeTranslateError
Unicode Error in conversion Warning
The base class for warnings DeprecationWarning
A warning about abandoned features FutureWarning
A warning about future semantic changes in construction OverflowWarning
Old about auto promotion to long form (long) Warning of PendingDeprecationWarning
A warning that features will be discarded RuntimeWarning
Suspicious runtime behavior (runtime behavior) Warning of SyntaxWarning
A dubious grammatical warning UserWarning
Warnings generated by user code The general structure of the exception class is as follows :
At the endThis is about Python This is the end of the article on how to handle exception and error reporting methods , More about Python Please search the previous articles of the software development network or continue to browse the following related articles. I hope you will support the software development network in the future !