Home >Backend Development >Python Tutorial >What are the methods for catching and handling exceptions in Python
refers to errors that occur when parsing the code. When the code does not comply with Python syntax rules, the Python interpreter will report a SyntaxError syntax error during parsing, and at the same time, it will clearly point out the earliest statement where the error was detected. For example:
print "Hello,World!"
We know that Python 3.0 no longer supports the above writing method, so at run time, the interpreter will report the following error:
SyntaxError: Missing parentheses in call to 'print'
Syntax error Most of them are caused by the developer's negligence. They are real errors and cannot be tolerated by the interpreter. Therefore, the program can only be executed if all grammatical errors in the program are corrected.
Run-time error means that the program is syntactically correct, but an error occurs during runtime. For example:
a = 1/0
The above code means "divide 1 by 0 and assign it to a. Because 0 is meaningless as a divisor, the following error will occur after running:
Traceback (most recent call last): File "75aa4689b22f032d3efc07fedce8baa7", line 1, in 4225fa317875f3e92281a7b1a5733569 1/0 ZeroDivisionError: division by zero
In the above running output results, the first two paragraphs indicate the location of the error, and the last sentence indicates the type of error. In Python, This kind of error situation during runtime is called Exceptions.
There are many such exceptions. The common exceptions are as follows:
Exception type | Meaning | Instance |
AssertionError | When assert keyword When the condition is false, the program will stop and throw this exception | ##>>> assert 1>0>>> assert 1c9ca515cc9b43ce6669d165b86f09bdf>> s="hello">>> s.lenAttributeError: 'str' object has no attribute'len' |
The index exceeds the range of the sequence and this exception will be thrown | >>> s="hello">>> s[5]IndexError: string index out of range | |
Search in dictionary This exception is thrown when a keyword does not exist | >>> demo_dict={"age": 20}>>> demo_dict[" name"]KeyError: 'name' | |
This exception is thrown when trying to access an undeclared variable | >>> helloNameError: name 'hello' is not defined | |
Invalid operations between different types of data | >>> 1 "2" |
TypeError: unsupported operand type(s) for : 'int' and 'str ' |
The divisor in the division operation is 0. This exception is raised | >>> a = 1 /0 |
ZeroDivisionError: division by zero |
The above is the detailed content of What are the methods for catching and handling exceptions in Python. For more information, please follow other related articles on the PHP Chinese website!