python exception handling (IndexError, TypeError, NameError, FileNotFoundError)

Record python exception handling method:

1.IndexError: string index out of range

my = 'I Love Python!'

my[20]

How to avoid: When you encounter this error, the string index is out of range. Check whether the string you index is out of range. Just don't go out of range.

2.IndexError: list index out of range

my = ['Python!','C++']

my[2]

How to avoid: When you encounter this error, the list index is out of range, just check the length of the list index, it cannot be exceeded.

3.TypeError: can only concatenate str (not "int") to str

number = '123'

b = number+123

Avoidance method: If such an error occurs, check whether the data type is correct. For example, during the operation, int type data is operated on int type data, and str type data can only be operated on str type data.

4.TypeError: 'NoneType' object is not subscriptable

list1 = None

print(list1[0])

Workaround: list1 is assigned None, which means it does not have any elements. When you try to access the first element of list1 using [0], Python will raise a TypeError because the element cannot be accessed from a  NoneType  object. Make sure that the object you want to access the element or attribute is not None.

5.NameError: name 'y' is not defined

print(y)

How to avoid: In the early days of learning python, you often encounter such errors. NameError is the most common and most commonly encountered built-in error class name. It means that a NameError will be raised if the variable name cannot be found. The solution is that it must be defined first. Before you can use this variable, if you want to output the string "y', or if you want to define y as a certain data type, you must first tell the program what this object is.

6.FileNotFoundError: [Errno 2] No such file or directory: '1.txt'

open('1.txt')

How to avoid: When we want to open a txt text, the above error is reported and the text cannot be opened. At this time, we need to check whether the text is present in the path where the project is run, or whether the name of the text is correct. , whether the text format is correct, basically checking these can solve the exception.

Some common exception handling is like this.

Guess you like

Origin blog.csdn.net/pengneng123/article/details/133379238