Fundamentals of python (XIV): errors and exceptions

Python sophomore 2021-07-25 01:58:27
fundamentals python xiv errors exceptions

Errors in programs are often referred to as bug , At work, we not only need to change the... In our own program bug , You also need to change... In other people's programs bug , New projects include bug To change , Old projects also have bug To change , so to speak bug Almost throughout a programmer's career ... We usually will bug It is divided into Error( error ) and Exception( abnormal ), Let's learn more about Python Medium error and abnormal .


error It usually refers to... In the program Grammar mistakes or Logic error , To pass through two Python Take a look at :

Examples of syntax errors

#print There's less in the front : if True print("hello python")

We usually write programs using development tools , such as : I use Pycharm Tool compilation Python Program , Grammatical errors like this , When writing a program , The compiler will detect it and prompt us , therefore , The program we write will hardly have this problem .

Examples of logical errors

#0 Can't be a divisor a = 5b = 0print(a/b)
# Execution results :ZeroDivisionError: division by zero

The logic error compiler will not prompt us , therefore , When we write the program , Have a certain understanding of some basic common sense , thus , Avoid logical errors .


Even if Python The syntax of the program is correct , When it's running , There is also the possibility of mistakes , Errors detected during runtime are called exceptions ; Most exceptions are not handled by the program , All in the form of error messages .

Python Built-in exception

Let's first look at the exception hierarchy :

BaseException +-- SystemExit +-- KeyboardInterrupt +-- GeneratorExit +-- Exception +-- StopIteration +-- StopAsyncIteration +-- ArithmeticError | +-- FloatingPointError | +-- OverflowError | +-- ZeroDivisionError +-- AssertionError +-- AttributeError +-- BufferError +-- EOFError +-- ImportError | +-- ModuleNotFoundError +-- LookupError | +-- IndexError | +-- KeyError +-- MemoryError +-- NameError | +-- UnboundLocalError +-- OSError | +-- BlockingIOError | +-- ChildProcessError | +-- ConnectionError | | +-- BrokenPipeError | | +-- ConnectionAbortedError | | +-- ConnectionRefusedError | | +-- ConnectionResetError | +-- FileExistsError | +-- FileNotFoundError | +-- InterruptedError | +-- IsADirectoryError | +-- NotADirectoryError | +-- PermissionError | +-- ProcessLookupError | +-- TimeoutError +-- ReferenceError +-- RuntimeError | +-- NotImplementedError | +-- RecursionError +-- SyntaxError | +-- IndentationError | +-- TabError +-- SystemError +-- TypeError +-- ValueError | +-- UnicodeError | +-- UnicodeDecodeError | +-- UnicodeEncodeError | +-- UnicodeTranslateError +-- Warning +-- DeprecationWarning +-- PendingDeprecationWarning +-- RuntimeWarning +-- SyntaxWarning +-- UserWarning +-- FutureWarning +-- ImportWarning +-- UnicodeWarning +-- BytesWarning +-- ResourceWarning

Through the above exception hierarchy , We can see clearly ,BaseException For all exception base classes , It is divided into :SystemExit、KeyboardInterrupt、GeneratorExit、Exception Four types of anomalies ,Exception The base class for all non system exit class exceptions ,Python Advocate inheritance Exception Or its subclass to derive a new exception ;Exception The following contains a variety of common exceptions, such as :MemoryError( out of memory )、BlockingIOError(IO abnormal )、SyntaxError( Syntax error exception )... For detailed instructions, you can see the following list :

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

exception handling

Python The program catches exceptions using try/except sentence , Let's take an example :

#1、 The divisor is 0, Uncaught exception def getNum(n): return 10 / nprint(getNum(0))# Output results :ZeroDivisionError: division by zero
#2、 Capture exception def getNum(n): try: return 10 / n except IOError: print('Error: IOError argument.') except ZeroDivisionError: print('Error: ZeroDivisionError argument.')print(getNum(0))''' Output results :Error: ZeroDivisionError argument.None'''

try The statement works as :

  • First , perform try Clause ( stay try and except The part between keywords );

  • If no exceptions occur , except Clause stay try After the statement is executed, it is ignored ;

  • If in try Exception occurred during clause execution , Then the rest of the clause will be ignored ;

  • If the exception matches except The exception type specified after the keyword , Just execute the corresponding except Clause , And then go ahead and do it try Code after statement ;

  • If an exception happens , stay except There is no matching branch... In the clause , It will pass on to the next level try In the sentence ;

  • If the corresponding processing statement cannot be found in the end , It becomes a Unhandled exception , Terminate program operation , Display prompt message .

try/except The statement can also have a else、finally Clause , Examples are as follows :

def getNum(n): try: print('try --> ',10 / n) except ZeroDivisionError: print('except --> Error: ZeroDivisionError argument.') else: print('else -->') finally: print('finally -->')
'''1、 call :getNum(0) Output results :except --> Error: ZeroDivisionError argument.finally -->
2、 call :getNum(1) Output results :try --> 10.0else -->finally -->'''

among ,else Clause can only appear in all except After Clause , Execute only if there are no exceptions ;finally Clause at the end , Execute whether or not an exception occurs .

Throw an exception

Use raise Statement allows you to force a specified exception to be thrown , Exception to be thrown by raise The unique parameter ID of , It must be an exception instance or exception class ( Inherited from Exception Class ), Such as :

raise NameError('HiThere')

Custom exception

Normally ,Python The exception type provided is already suitable for our use , But sometimes we have customized needs , We can customize exception classes , Inherited from Error or Exception Class is OK , Look at an example :

# Custom exception classes MyExcclass MyExc(Exception): # Inherit Exception class def __init__(self, value): self.value = value def __str__(self): if self.value == 0: return ' The dividend cannot be zero 0'# Custom method def getNum(n): try: if n == 0: exc = MyExc(n) print(exc) else: print(10 / n) except: pass'''1、 call getNum(1), The output is :10.0
2、 call getNum(0), The output is : The dividend cannot be zero 0'''

In this custom exception example , When parameters n Not for 0 when , It's normal , When n be equal to 0, Throw an exception , Custom exceptions are rarely used in practical applications , Understanding can .




本文为[Python sophomore]所创,转载请带上原文链接,感谢

  1. 小白量化投资交易入门课(python入门金融分析)
  2. Python:PyCharm选择性忽略PEP8警告
  3. Python: pychar selectively ignores pep8 warnings
  4. Django-模板
  5. Django template
  6. Python正则表达式大全
  7. 最全Python正则表达式来袭
  8. A python knowledge for Xiaobai
  9. 2. Flexible pandas index
  10. 1. Get to know pandas
  11. See how I use Python to create a magic with baby (one play can play for a day)?
  12. Wow, python can do real-time translation
  13. Python经典编程习题100例
  14. 100 examples of Python classic programming exercises
  15. Invincible, with Python for English teachers to develop a magic tool for English composition correction (support primary school to IELTS)
  16. 抖音数据采集教程,最全python库selenium自动化使用
  17. Pandas 11-综合练习
  18. Pandas 11 - comprehensive exercises
  19. Pandas基础|用户游览日志时间合并排序
  20. python自学 第三章 python语言基础之保留字、标识符与内置函数
  21. python学习例程3-函数
  22. Python GUI 之Tkinter小结 - 知乎
  23. Pandas foundation | user travel log time merge sort
  24. Chapter 3 reserved words, identifiers and built-in functions of the foundation of Python
  25. Tkinter summary of Python GUI - Zhihu
  26. 【Python常用包】itertools
  27. Itertools
  28. [Python] Matplotlib 图表的绘制和美化技巧
  29. Drawing and beautifying skills of [Python] Matplotlib chart
  30. Drawing and beautifying skills of [Python] Matplotlib chart
  31. Python序列之列表(一)
  32. Python解析库lxml与xpath用法总结
  33. Python解析库lxml与xpath用法总结
  34. Usage Summary of Python parsing library lxml and XPath
  35. Usage Summary of Python parsing library lxml and XPath
  36. Python web/HTML GUI
  37. Why is sanic better than Django flame?
  38. Wechat applet Python sends subscription message
  39. Invincible, with Python for English teachers to develop an English composition correction artifact (support primary school to IELTS)
  40. How can I use Python to create a magic with children (one can play for one day)?
  41. Pandas module
  42. Machine learning in Python - Boston house price forecast
  43. 50 Great Python modules
  44. Share the survival status of Python practitioners and tell you the real salary of general programmers
  45. Pandas basic operation update
  46. Python Programming day02 Python operator
  47. Usage Summary of Python parsing library lxml and XPath
  48. 1. First meeting pandas
  49. Conversion between Python and base conversion between Python and base
  50. Basics of Python
  51. Fundamentals of python (8): time related modules
  52. Fundamentals of python (I): necessary knowledge for getting started
  53. Operators in Python 3
  54. The list of national computer non graduate schools (captured by Python), just look at this one!
  55. Python data visualization: Seaborn
  56. Quick start pandas (lower)
  57. Operators in Python 3
  58. Python tarfile module
  59. Python basic syntax