Keep creating , Accelerate growth ! This is my participation 「 Nuggets day new plan · 6 Yuegengwen challenge 」 Of the 24 God , Click to see the event details
today Python The content of the notes is :
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 .
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())
x
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 10: 'x'
Copy code
In the above code ,ValueError
Is an exception , By exception information , We can find the wrong line number .
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)
break
except 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
Copy code
In the above procedure :
try
and except
;int() function
Will throw out ValueError abnormal
;try block
Detected in ValueError abnormal
when , It will end try Block subsequent code ;except block
Code for ;except ValueError:
After the code is executed , The program will continue from while sentence
Continue with the beginning of ;int() function
Will throw out ValueError abnormal
, that try:
After break sentence
They don't execute , The program will cycle all the time ;int() function
It won't throw out ValueError abnormal
,try block
Can continue to execute , Until I met break sentence
, The program will exit the loop ;try
And except
Statement is used to detect try Exception in statement block , And let except Statement to catch and handle exceptions ; 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 :
try
Statement blocks in execute first .- If
try
In statement block An exception occurred during the execution of a statement ,Python
Just jump toexcept
part , Judge from top to bottom Whether the exception object thrown is related toexcept
The following exception classes match , And execute the first... That matches the exceptionexcept
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 matchexcept
Clause , There is no one without a matching typeexcept
part , The exception will be submitted to the upper layertry/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 performelse
Statement block after statement .- After execution
except
After the exception handling statement orelse
After the following statement block , The program must executefinally
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 aexcept
Sentence block ,else
andfinally
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 .
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)Exception
Regular error base class StopIteration
Iterators have no more values GeneratorExit
generator (generator) An exception occurs to notify the exit 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 standard exception class structure is roughly as follows :
Okay , Today's notes are here , Welcome to the comment area to discuss .