程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

[Python]: how to handle Python exception errors?

編輯:Python

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

1️⃣ Write it at the front

today 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 .

2️⃣ 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())
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 .

3️⃣ 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)
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 :

  • 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() function Will throw out ValueError abnormal ;
  • be try block Detected in ValueError abnormal when , It will end try Block subsequent code ;
  • Turn to execution except block Code for ;
  • When except ValueError: After the code is executed , The program will continue from while sentence Continue with the beginning of ;
  • It should be noted that , As long as the input is not an integer ,int() function Will throw out ValueError abnormal , that try: After break sentence They don't execute , The program will cycle all the time ;
  • Last , When the input value is an integer ,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 ;

4️⃣try And except

  • try 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 :

  • try Statement blocks in execute first .
  • If try In statement block An exception occurred during the execution of a statement ,Python Just jump to except part , Judge from top to bottom 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 .

* Example

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 .

5️⃣python Standard exception

Exception name describe 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 SyntaxErrorPython Grammar mistakes IndentationError The indentation error TabErrorTab Mixed with Spaces SystemError General interpreter system error TypeError Invalid operation on type ValueError Invalid parameter passed in UnicodeErrorUnicode Related errors UnicodeDecodeErrorUnicode Error in decoding UnicodeEncodeErrorUnicode Error in coding UnicodeTranslateErrorUnicode 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 :

6️⃣ At the end

Okay , Today's notes are here , Welcome to the comment area to discuss .


  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved