One picture flow: all built-in exceptions in Python


Hi everyone, and welcome to Crossin's programming classroom!

When writing a program, you may often report some exceptions. On the one hand, it is because your own negligence caused the program to give error messages. On the other hand, it is because some exceptions are inevitable when the program is running, such as when crawling. There are several webpages with inconsistent structures. At this time, the two webpages with the same set of codes will make mistakes, so we need to catch the exceptions to prevent the program from terminating due to error messages.

Python has many built-in exceptions, which means that Python developers have considered in advance that such errors may occur during user programming, so creating these built-in exceptions can quickly and accurately feedback error information to users to help find bugs in the code.

All the built-in exceptions and trigger conditions are also given in the official Python documentation. In order to have a better reading experience, I have organized all the exceptions and trigger conditions into a mind map (click to enlarge, view horizontally):

The HD version download address is attached at the end of the article

The following is a separate introduction to several common exceptions, and an in-depth understanding of which exception will be triggered under what conditions through examples.

1、 SyntaxError

SyntaxError is mainly caused by errors in Python syntax, such as missing colons, multiple quotation marks, etc. A little carelessness during programming will cause errors. It should be the most common type of abnormal error.

In [1]: While True print('1')
 File "<ipython-input-1-8ebf67bb4c2b>", line 1
 While True print('1')^
SyntaxError: invalid syntax

2、 TypeError

TypeError is a type error, that is, it is raised when an operation or function is applied to an object of an inappropriate type, such as adding and subtracting integer and character types, subtracting between two lists, and so on.

In [8]: a =[1,2];b =[2,3]
In [9]: a-b
---------------------------------------------------------------------------
TypeError                                 Traceback(most recent call last)<ipython-input-9-5ae0619f8fe1>in<module>---->1 a-b

TypeError: unsupported operand type(s)for-:'list' and 'list'

3、 IndexError

IndexError refers to an error in the index. For example, the most common subscript index exceeds the sequence boundary. For example, when a sequence m has only three elements, it tries to access m[4].

In [16]: m =[1,2,3]
In [17]: m[4]---------------------------------------------------------------------------
IndexError                                Traceback(most recent call last)<ipython-input-17-94e0dfab3ff6>in<module>---->1 m[4]

IndexError: list index out of range

4、 KeyError

KeyError is a keyword error, this exception mainly occurs in the dictionary, such as when the user tries to access a key that does not exist in the dictionary will be raised.

In [18]: dict_ ={'1':'yi','2':'er'}
In [19]: dict_['3']---------------------------------------------------------------------------
KeyError                                  Traceback(most recent call last)<ipython-input-19-c2e43847635f>in<module>---->1 dict_['3']

KeyError:'3'

5、 ValueError

ValueError is a value error, which is raised when the user passes in a value that the caller does not expect, even if the type of the value is correct, for example, if you want to get the index of a non-existent value in a list.

In [22]: n =[1,2,3]
In [23]: n.index(4)---------------------------------------------------------------------------
ValueError                                Traceback(most recent call last)<ipython-input-23-9a1887cf29d7>in<module>---->1 n.index(4)

ValueError:4 is not in list

6、 AttributeError

AttributeError is an attribute error, which is raised when a user tries to access an attribute that does not exist in an object. For example, a list has an index method, but a dictionary does not. Therefore, calling this method on a dictionary object will raise the exception.

In [25]: dict_ ={'1':'yi','2':'er'}
In [26]: dict_.index('1')---------------------------------------------------------------------------
AttributeError                            Traceback(most recent call last)<ipython-input-26-516844ad2563>in<module>---->1 dict_.index('1')

AttributeError:'dict' object has no attribute 'index'

7、 NameError

NameError refers to an error in the variable name, for example, it will be triggered when the user tries to call a variable that has not been assigned or initialized.

In [27]:print(list_)---------------------------------------------------------------------------
NameError                                 Traceback(most recent call last)<ipython-input-27-87ebf02ffcab>in<module>---->1print(list_)

NameError: name 'list_' is not defined

8、 FileNotFoundError

FileNotFoundError is an open file error, which is raised when the user tries to open a file that does not exist in read mode.

In [29]: fb =open('./list','r')---------------------------------------------------------------------------
FileNotFoundError                         Traceback(most recent call last)<ipython-input-29-1b65fe5400ea>in<module>---->1 fb =open('./list','r')

FileNotFoundError:[Errno 2] No such file or directory:'./list'

9、 StopIteration

StopIteration is an iterator error. When the access is continued until the last value of the iterator, this exception will be raised to remind the user that there is no value in the iterator for access.

In [30]: list1 =[1,2]
In [31]: list2 =iter(list1)
In [33]:next(list2)
Out[33]:1

In [34]:next(list2)
Out[34]:2

In [35]:next(list2)---------------------------------------------------------------------------
StopIteration                             Traceback(most recent call last)<ipython-input-35-5a5a8526e73b>in<module>---->1next(list2)

10、 AssertionError

AssertionError is an assertion error. When a user uses an assertion statement to detect an exception, if the expression detected by the assertion statement is false, this exception will be raised.

In [45]: list3 =[1,2]

In [46]: assert len(list3)>2---------------------------------------------------------------------------
AssertionError                            Traceback(most recent call last)<ipython-input-46-ffd051e2ba94>in<module>---->1 assert len(list3)>2

AssertionError:

The above exceptions should be part of the higher frequency encountered in usual programming. For more types of exceptions, please refer to the above mind map or refer to official documents. Of course, Python also supports users to customize exceptions according to their needs.

Python also has powerful functions for handling exceptions, such as catching exceptions, actively throwing exceptions, etc., mainly in the following ways:

The mind map of this article is drawn using Baidu Mind Map, and I also put it in the online disk, you can add and modify it yourself.

Mind map download:

https://pan.baidu.com/s/1X4NIoRec1umU6Dhh9GobQQ

Extraction code: tcwy

Official documents:

https://docs.python.org/3/library/exceptions.html#base-classes

Author: toffee cat

Source: Meow Talking Python


_ Recommendations of previous articles_

[ One article teaches you to understand the abnormal information in Python](http://mp.weixin.qq.com/s?__biz=MjM5MDEyMDk4Mw==&mid=2650168776&idx=2&sn=e965016f826c8c90062323f7a2a26e0b&chksm=be4b50b0893bc9a64477308eb&chksm=be4b50b0893bc9a64477#be4b50b0893bc9a64477


Recommended Posts

One picture flow: all built-in exceptions in Python
Learn Python in one minute | Object-oriented (Chinese)
Learn Python in one minute | Python functions (on)
Learn Python in One Minute | Object Oriented (Part 1)
One article to get regular expressions in Python
Python review one
Functions in python