What are the methods for catching and handling exceptions in Python
WBOY
Release: 2023-05-22 23:37:17
forward
1860 people have browsed it
1 | Syntax error
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!"
Copy after login
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'
Copy after login
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.
2 | Run-time error
Run-time error means that the program is syntactically correct, but an error occurs during runtime. For example:
a = 1/0
Copy after login
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 "<pyshell#0>", line 1, in <module> 1/0 ZeroDivisionError: division by zero
Copy after login
3 |Other exceptions
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 1<0AssertionError
AttributeError
Exception thrown when the object attribute attempted to be accessed does not exist
>>> s="hello">>> s.lenAttributeError: 'str' object has no attribute'len'
IndexError
The index exceeds the range of the sequence and this exception will be thrown
>>> s="hello">>> s[5]IndexError: string index out of range
KeyError
Search in dictionary This exception is thrown when a keyword does not exist
try:
a = int(input("输入被除数:"))
b = int(input("输入除数:"))
c = a / b
print("您输入的两个数相除的结果是:", c )
except (ValueError, ArithmeticError):
print("程序发生了数字格式异常、算术异常之一")
except :
print("未知异常")
print("程序继续运行")
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!
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn