Python exception handling

Ruochen 2021-02-23 10:28:54
python exception handling


abnormal

  • Errors in a broad sense can be divided into errors and anomalies
  • Mistakes are things that can be avoided
  • Exception refers to the premise that the syntax and logic are correct , What happened
  • stay python in , An exception is a class , Can handle and use

Classification of exceptions


BaseException The base class for all exceptions
Exception Base class for common errors
ArithmeticError Base class for all numerical errors
Warning The base class for warnings
AssertError Assertions (assert) Failure
AttributeError Trying to access unknown object properties
DeprecattionWarning A warning about abandoned features
EOFError User input end of file flag EOF(Ctrl+d)
FloattingPointError Floating point error
FutureWarning A warning about future semantic changes in construction
GeneratorExit generator.close() When the method is called
ImportError When the import module fails
IndexError Index out of range of sequence
KeyError Look up a nonexistent keyword in the dictionary
KeyboardInterrupt User input interrupt key (Ctrl+c)
MemoryError out of memory ( You can free memory by deleting objects )
NamerError Try to access a variable that doesn't exist
NotImplementedError A method that has not yet been implemented
OSError An exception generated by the operating system ( For example, open a file that doesn't exist )
OverflowError The numerical operation exceeds the maximum limit
OverflowWarning Old about auto promotion to long form (long) Warning of
PendingDeprecationWarning A warning that features will be abandoned
ReferenceError Weak reference (weak reference) Trying to access an object that has been reclaimed by the garbage collection mechanism
RuntimeError General runtime errors
RuntimeWarning Suspicious operational behavior (runtime behavior) Warning of
StopIteration Iterators have no more values
SyntaxError Python A grammatical error of
SyntaxWarning A dubious grammatical warning
IndentationError The indentation error
TabError Tab Mixed with spaces
SystemError Python Compiler system error
SystemExit Python Compiler process is shut down
TypeError Invalid operation between different types
UnboundLocalError Accessing an uninitialized local variable (NameError Subclasses of )
UnicodeError Unicode Related errors (ValueError Subclasses of )
UnicodeEncodeError Unicode Errors in coding (UnicodeError Subclasses of )
UnicodeDecodeError Unicode Error in decoding (UnicodeError Subclasses of )
UserWarning Warnings generated by user code
ValueError Invalid parameter passed in
ZeroDivisionError Divisor is zero.
l = [1,2,3,4,5]
# Divide by zero error
num = int(input("Please input your num: "))
print(100/num)
Please input your num: 0
---------------------------------------------------------------------------
ZeroDivisionError Traceback (most recent call last)
<ipython-input-1-8abb196ce2aa> in <module>
2 # Divide by zero error
3 num = int(input("Please input your num: "))
----> 4 print(100/num)
ZeroDivisionError: division by zero

exception handling

  • There is no guarantee that the program will always run correctly
  • however , It must be ensured that the problems that the program gets in the worst case are properly managed
  • python The syntax of the exception handling module is :

    try:
    Try to implement an operation ,
    If nothing goes wrong , The task can be accomplished
    If there is an anomaly , Throw the exception out of the current code block and try to resolve the exception
    except Exception types 1:
    Solution 1: Used to try to handle exceptions here to solve problems
    except Exception types 2:
    Solution 2: Used to try to handle exceptions here to solve problems
    except ( Exception types 1, Exception types 2...):
    Solution : Use the same handling for multiple exceptions
    except:
    If nothing goes wrong , The code here will be executed
    finally:
    Code to be executed with or without exception
    
  • technological process

    1. perform try The following statement
    2. If there is an anomaly , It's in except Statement to find the corresponding abnormal disease for processing
    3. If nothing goes wrong , execute else Statement content
    4. Last , Whether or not there is an exception , To perform all finally sentence
  • except except( At least one ) outside ,else and finally Optional
# Simple exception cases
try:
num = int(input("Please input your number:"))
rst = 100/num
print(" The result is :{}".format(rst))
except:
print(" Input error ")
# exit It means to quit the program
exit()
Please input your number:0
Input error
# Simple exception cases
# Give tips
try:
num = int(input("Please input your number:"))
rst = 100/num
print(" The result is :{}".format(rst))
# After catching the exception , Instantiate the exception , The error message will be in the instance
# Pay attention to the following
# The following statement is to capture ZeroDivisionError Exception and instantiate instance e
except ZeroDivisionError as e:
print(" Input error ")
print(e)
# exit It means to quit the program
exit()
# Simple exception cases
# Give tips
try:
num = int(input("Please input your number:"))
rst = 100/num
print(" The result is :{}".format(rst))
# If it's multiple error The situation of
# The more specific mistakes we need to make , More and more forward
# In the exception class inheritance relationship , The more subclass exceptions , The more you put it forward ,
# The more the exception of the parent class , The more you put it back 、
# When handling exceptions , Once an exception is intercepted , You will not continue to look down , Go straight to the next
# Code , That is to say finally execute finally sentence , If not, execute the next big statement
except ZeroDivisionError as e:
print(" Input error ")
print(e)
# exit It means to quit the program
exit()
except NameError as e:
print(" Wrong name ")
print(e)
except AttributeError as e:
print(" Property error ")
print(e)
exit()
# Base class for common errors
# If you write the following sentence , Common exceptions will be blocked
# And the following sentence must be the last one excepttion
except Exception as e:
print(" I made a mistake without knowing ")
print(e)
except ValueError as e:
print("NO>>>>>>>>>>>")
print("hahaha")
Please input your number:ffff
I made a mistake without knowing
invalid literal for int() with base 10: 'ffff'
hahaha

The user manually raises an exception

  • When something , When the user wants to throw an exception himself , have access to
  • raise Keyword to throw an exception
# raise Case study
try:
print("I love you")
print(3.1415926)
# Manually throw an exception
# Pay attention to the grammar :raise ErrorClassName
raise ValueError
print(" It's not over yet ")
except NameError as e:
print("NameError")
except ValueError as e:
print("ValueError")
except Exception as e:
print(" There are abnormal ")
finally:
print(" I'm sure it will be carried out ")
I love you
3.1415926
ValueError
I'm sure it will be carried out
# raise Case study -2
# Custom exception
# We need to pay attention to : Custom exception must be a subclass of system exception
class DanaValueError(ValueError):
pass
try:
print("I love you")
print(3.1415926)
# Manually throw an exception
# Pay attention to the grammar :raise ErrorClassName
raise DanaValueError
print(" It's not over yet ")
except NameError as e:
print("NameError")
# except DanaValueError as e:
# print("DanaError")
except ValueError as e:
print("ValueError")
except Exception as e:
print(" There are abnormal ")
finally:
print(" I'm sure it will be carried out ")
I love you
3.1415926
ValueError
I'm sure it will be carried out
# else Sentence case
try:
num = int(input("Please input your number:"))
rst = 100/num
print(" The result is :{}".format(rst))
except Exception as e:
print("Exceptiong")
else:
print("No Exception")
finally:
print(" I'll be executed anyway ")
Please input your number:0
Exceptiong
I'll be executed anyway

About custom exceptions

  • As long as it is raise abnormal , Custom exception is recommended
  • When customizing exceptions , Generally, it includes the following contents :

    • Customize the exception code when an exception occurs
    • Customize the question prompt after exception
    • Customize the number of rows where an exception occurs
  • The ultimate goal is , Once something goes wrong , Convenient for programmers to quickly locate the error site
版权声明
本文为[Ruochen]所创,转载请带上原文链接,感谢
https://pythonmana.com/2021/02/20210223102604924h.html

  1. 阿里、华为Python工程师总结的实用技巧,只有你还没看?
  2. 酸了!看到抖音上Python程序员晒得工资条......
  3. Python基础之:数字字符串和列表
  4. Importing excel into database adaptively by Python
  5. Python安装教程
  6. Python安装教程
  7. From Xiaobai to master, here is a guide to pandas
  8. [Python] drawing method of stem leaf diagram and compound pie diagram
  9. Drawing of Python geoplot spatial kernel density estimation map
  10. Python Seaborn economist's classic chart imitation
  11. Python space drawing - regionmask mask operation example
  12. Python space drawing - cartopy longitude and latitude add
  13. Python pykrige package Kriging interpolation calculation and visual rendering
  14. Python batch resampling, mask, slope extraction
  15. Python - Analysis of reachable circle of multiple traffic modes
  16. Python space drawing bubble drawing
  17. Python 3 multithreading and Mongo 100 million consumption log data fresh demo
  18. ARIMA model for predicting time series of CO2 concentration
  19. python isinstance()
  20. How to modify tens of thousands of file names with one key in Python
  21. Python notes: List
  22. Translation: practical Python Programming 02_ 03_ Formatting
  23. Python中的四种队列(queue)、堆(heap)
  24. Side effects of Python mutable types as default parameters of functions
  25. This is the best Python tutorial I've ever seen: ten minutes to get to know python
  26. 使用python编写量子线路打印的简单项目,并使用Sphinx自动化生成API文档
  27. Python happy enemy: crawler and anti crawler with a solution to give you New Year
  28. 使用python编写量子线路打印的简单项目,并使用Sphinx自动化生成API文档
  29. When writing python, you will encounter the following error: modulenotfounderror: no module named ' email.mime '; 'email' is not a package
  30. Python class call and private and public property method call
  31. Proprietary methods for Python classes
  32. Foundation of Python: number string and list
  33. Foundation of Python: number string and list
  34. Foundation of Python: number string and list
  35. 华为 Python网络自动化
  36. Python Cannot open E:\Python36\Scripts\pip-script.py
  37. Peeping into the future is not a dream, python data analysis is easy to achieve
  38. The practical skills summed up by Alibaba and Huawei Python engineers, only you haven't seen them yet?
  39. Sour! See the Python programmers on the tiktok get the pay slip...
  40. Foundation of Python: number string and list
  41. Python installation tutorial
  42. Python installation tutorial
  43. This article will familiarize you with the transformation process of Python - > Cafe - > om model
  44. Four kinds of queues and heaps in Python
  45. Using Python to write a simple project of quantum circuit printing, and using Sphinx to automatically generate API documents
  46. Using Python to write a simple project of quantum circuit printing, and using Sphinx to automatically generate API documents
  47. Huawei Python Network Automation
  48. Python Cannot open E:\Python36\Scripts\pip- script.py
  49. 找不到Python问题解决
  50. PHP和Python哪个更有市场前景?我学的是PHP
  51. Python problem resolution not found
  52. Which has more market prospects, PHP or Python? I studied PHP
  53. Foundation of Python: number string and list
  54. python 编码问题之终极解决
  55. The ultimate solution to the problem of Python coding
  56. 能取值亦能赋值的Python切片
  57. Python slice with value and value
  58. 能取值亦能赋值的Python切片
  59. Python slice with value and value
  60. python 异常处理