When writing programs, often quoted may be some abnormal, big reason is that his carelessness led to the incorrect information, program is given on the other hand is because runs some exceptions are inevitable, such as when the crawler may have several web page structure, then the structure of the two pages with the same set of code will go wrong, So we need to catch exceptions to prevent the program from terminating because of error messages.

Python has a lot of built-in exceptions, which means that the Python developers thought ahead of time that users might get this kind of error when programming, so they created these built-in exceptions to quickly and accurately inform users of errors and help find bugs in their code.

All the built-in exceptions and trigger conditions are also listed in the Official Python documentation. For a better reading experience, I’ve organized all the exceptions and trigger conditions into a mind map:

At the end of the article with the hd version of the way to get, partners can be directly drawn to the end of the picture, the following is a separate introduction for several common exceptions, through examples to understand which exceptions will trigger under what conditions.

1, SyntaxError

A SyntaxError is an error in Python syntax, such as missing colons or multiple quotes.

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

2, TypeError

TypeError is a TypeError, which is raised when an operation or function is applied to an object of the wrong type, such as adding and subtracting integers from characters, subtracting between 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'Copy the code

3, IndexError

IndexError is an IndexError, such as the most common subscript index exceeding the sequence boundary, such as an attempt to access m when a sequence m has only three elements [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
Copy the code

4, KeyError

KeyError is a keyword error, an exception that occurs mostly in dictionaries, such as when a user tries to access a key that does not exist in the dictionary.

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'
Copy the code

5, ValueError

ValueError is a ValueError, raised when the user passes in a value that the caller does not expect, even if the value is of the correct type, such as trying to get an index of a nonexistent 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 listCopy the code

6, AttributeError

AttributeError is an AttributeError that is raised when the user tries to access a nonexistent attribute of an object, such as a list that has an index method but a dictionary doesn’t, so calling the method on a dictionary object raises this 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'
Copy the code

7, NameError

NameError is when a variable NameError occurs, such as when a user attempts to call a variable that has not yet been assigned or initialized.

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

NameError: name 'list_' is not defined
Copy the code

8 FileNotFoundError.

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

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'
Copy the code

9 StopIteration.

StopIteration is an iterator error. Accessing the last value of the iterator will raise this exception, reminding the user that there are no more values in the iterator to access.

In [30]: list1 = [1,2] In [31]: List2 = iter 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> ----> 1 next(list2)Copy the code

10, AssertionError

AssertionError is an AssertionError that is raised when the user detects an exception using an assertion statement if the expression detected by the assertion statement is false.

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:Copy the code

Python also allows users to customize exceptions based on their own needs, so I don’t want to give too much of an overview here.

Python also has some powerful functions, such as catching exceptions and actively throwing exceptions. There are several ways to handle exceptions:

  • 1.try … Except structure statement capture
  • 2.try … except … Finally structure statement capture
  • 3.try … except … Else structure statement capture
  • 4. The raise keyword proactively raises an exception
  • 5.try … raise … Except trigger exception
  • 6. Assert statements
  • 7. The Traceback module traces faults

In addition to the downloaded mind map, there is also an online version of the mind map, which I drew with Baidu Brain Map. If you think there is any unreasonable part of the map, you can edit it online on the web site according to your own ideas.

How to obtain: public number [sugar cat] background reply keyword “abnormal”.