Python exception handling

Ruochen_ 2021-02-23 10:20:40
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/20210223101347903t.html

  1. 利用Python爬虫获取招聘网站职位信息
  2. Using Python crawler to obtain job information of recruitment website
  3. Several highly rated Python libraries arrow, jsonpath, psutil and tenacity are recommended
  4. Python装饰器
  5. Python实现LDAP认证
  6. Python decorator
  7. Implementing LDAP authentication with Python
  8. Vscode configures Python development environment!
  9. In Python, how dare you say you can't log module? ️
  10. 我收藏的有关Python的电子书和资料
  11. python 中 lambda的一些tips
  12. python中字典的一些tips
  13. python 用生成器生成斐波那契数列
  14. python脚本转pyc踩了个坑。。。
  15. My collection of e-books and materials about Python
  16. Some tips of lambda in Python
  17. Some tips of dictionary in Python
  18. Using Python generator to generate Fibonacci sequence
  19. The conversion of Python script to PyC stepped on a pit...
  20. Python游戏开发,pygame模块,Python实现扫雷小游戏
  21. Python game development, pyGame module, python implementation of minesweeping games
  22. Python实用工具,email模块,Python实现邮件远程控制自己电脑
  23. Python utility, email module, python realizes mail remote control of its own computer
  24. 毫无头绪的自学Python,你可能连门槛都摸不到!【最佳学习路线】
  25. Python读取二进制文件代码方法解析
  26. Python字典的实现原理
  27. Without a clue, you may not even touch the threshold【 Best learning route]
  28. Parsing method of Python reading binary file code
  29. Implementation principle of Python dictionary
  30. You must know the function of pandas to parse JSON data - JSON_ normalize()
  31. Python实用案例,私人定制,Python自动化生成爱豆专属2021日历
  32. Python practical case, private customization, python automatic generation of Adu exclusive 2021 calendar
  33. 《Python实例》震惊了,用Python这么简单实现了聊天系统的脏话,广告检测
  34. "Python instance" was shocked and realized the dirty words and advertisement detection of the chat system in Python
  35. Convolutional neural network processing sequence for Python deep learning
  36. Python data structure and algorithm (1) -- enum type enum
  37. 超全大厂算法岗百问百答(推荐系统/机器学习/深度学习/C++/Spark/python)
  38. 【Python进阶】你真的明白NumPy中的ndarray吗?
  39. All questions and answers for algorithm posts of super large factories (recommended system / machine learning / deep learning / C + + / spark / Python)
  40. [advanced Python] do you really understand ndarray in numpy?
  41. 【Python进阶】Python进阶专栏栏主自述:不忘初心,砥砺前行
  42. [advanced Python] Python advanced column main readme: never forget the original intention and forge ahead
  43. python垃圾回收和缓存管理
  44. java调用Python程序
  45. java调用Python程序
  46. Python常用函数有哪些?Python基础入门课程
  47. Python garbage collection and cache management
  48. Java calling Python program
  49. Java calling Python program
  50. What functions are commonly used in Python? Introduction to Python Basics
  51. Python basic knowledge
  52. Anaconda5.2 安装 Python 库(MySQLdb)的方法
  53. Python实现对脑电数据情绪分析
  54. Anaconda 5.2 method of installing Python Library (mysqldb)
  55. Python implements emotion analysis of EEG data
  56. Master some advanced usage of Python in 30 seconds, which makes others envy it
  57. python爬取百度图片并对图片做一系列处理
  58. Python crawls Baidu pictures and does a series of processing on them
  59. python链接mysql数据库
  60. Python link MySQL database