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 学习笔记: List
  2. 翻译:《实用的Python编程》02_03_Formatting
  3. Is there any age requirement for learning Python? Is 30 OK?
  4. Professor Tsinghua! The most complete Python tutorial in 12 hours (free sharing at the end of the article)
  5. Using Python to develop defi project
  6. Detailed explanation of Python function
  7. Python 可变类型作为函数默认参数时的副作用
  8. What do Python engineers do? What's their future?
  9. 这是我见过最好的Python教程:十分钟带你认识Python
  10. Python欢喜冤家:爬虫与反爬虫带着处理方案来给大家拜年了
  11. Python - zip() function
  12. 写Python会遇到如下的错误:ModuleNotFoundError: No module named 'email.mime'; 'email' is not a package
  13. Python类的调用以及私有和公有属性方法的调用
  14. Python类的专有方法
  15. Python基础之:数字字符串和列表
  16. How did Python pioneers evaluate this language on their 30th birthday?
  17. Python基础之:数字字符串和列表
  18. Python基础之:数字字符串和列表
  19. 窥探未来不是梦,python数据分析轻松实现
  20. This article will familiarize you with the transformation process of Python - & gt; cafe - & gt; om model
  21. 阿里、华为Python工程师总结的实用技巧,只有你还没看?
  22. 酸了!看到抖音上Python程序员晒得工资条......
  23. Python基础之:数字字符串和列表
  24. Importing excel into database adaptively by Python
  25. Python安装教程
  26. Python安装教程
  27. From Xiaobai to master, here is a guide to pandas
  28. [Python] drawing method of stem leaf diagram and compound pie diagram
  29. Drawing of Python geoplot spatial kernel density estimation map
  30. Python Seaborn economist's classic chart imitation
  31. Python space drawing - regionmask mask operation example
  32. Python space drawing - cartopy longitude and latitude add
  33. Python pykrige package Kriging interpolation calculation and visual rendering
  34. Python batch resampling, mask, slope extraction
  35. Python - Analysis of reachable circle of multiple traffic modes
  36. Python space drawing bubble drawing
  37. Python 3 multithreading and Mongo 100 million consumption log data fresh demo
  38. ARIMA model for predicting time series of CO2 concentration
  39. python isinstance()
  40. How to modify tens of thousands of file names with one key in Python
  41. Python notes: List
  42. Translation: practical Python Programming 02_ 03_ Formatting
  43. Python中的四种队列(queue)、堆(heap)
  44. Side effects of Python mutable types as default parameters of functions
  45. This is the best Python tutorial I've ever seen: ten minutes to get to know python
  46. 使用python编写量子线路打印的简单项目,并使用Sphinx自动化生成API文档
  47. Python happy enemy: crawler and anti crawler with a solution to give you New Year
  48. 使用python编写量子线路打印的简单项目,并使用Sphinx自动化生成API文档
  49. When writing python, you will encounter the following error: modulenotfounderror: no module named ' email.mime '; 'email' is not a package
  50. Python class call and private and public property method call
  51. Proprietary methods for Python classes
  52. Foundation of Python: number string and list
  53. Foundation of Python: number string and list
  54. Foundation of Python: number string and list
  55. 华为 Python网络自动化
  56. Python Cannot open E:\Python36\Scripts\pip-script.py
  57. Peeping into the future is not a dream, python data analysis is easy to achieve
  58. The practical skills summed up by Alibaba and Huawei Python engineers, only you haven't seen them yet?
  59. Sour! See the Python programmers on the tiktok get the pay slip...
  60. Foundation of Python: number string and list