This article brings you what are the exceptions in python? The detailed introduction of exceptions in python has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.
Python's exceptions are divided into two types: 1) Syntax error. If the code does not pass the syntax detection of the Python interpreter, the code cannot be run. 2) Exception. The error detected during the running of the Python program is called an exception. When no exception handling is done, the program will be terminated and exception information will be prompted, such as: ① type conversion exception when converting string to number, ② file does not exist exception when reading file, ③ host unreachable exception during network link... ·wait. When an exception occurs in a Python script, we need to catch and handle it, otherwise the program will terminate execution. After all, no one wants the program they are using to suddenly crash
1. Syntax error
python Syntax errors are a problem that many beginners often encounter. This type of error is relatively low-level. You can reduce such errors by typing the code a few more times
>>> if Trur File "<stdin>", line 1 if Trur ^ SyntaxError: invalid syntax >>> print("as")) File "<stdin>", line 1 print("as")) ^ SyntaxError: invalid syntax
For example: Such an error is a syntax error. The if statement at the end of line 1 lacks ":", and the end of line 6 has too many ")"
2. Exceptions
1) Errors detected during runtime are called exceptions, and Python's syntax detection cannot detect such errors.
>>> int("aa") Traceback (most recent call last): File "<stdin>", line 1, in <module> ValueError: invalid literal for int() with base 10: 'aa' >>> f = open("aaa.txt","r") Traceback (most recent call last): File "<stdin>", line 1, in <module> FileNotFoundError: [Errno 2] No such file or directory: 'aaa.txt'
The 1st and 5th lines are where exceptions occur. Look at the exceptions Output information, as shown below
2) python’s standard exception class
BaseException is the base class of all exceptions, and Exception is the base class of regular errors.
Other python exception classes will not be described one by one. You can Baidu See
3.Exception handling
In order to improve the robustness of the program and prevent the program from crashing when an exception occurs, when necessary Exception handling is required
1) try-except: statement
① The simplest exception handling statement is as follows, when the try statement block When an exception occurs in , the following statements will no longer be executed (line 3), the exception is caught by except, and the program continues to execute downwards after executing the statement block in except (such as line 6). Note: Except is not followed by the exception type, and all exceptions are caught by default
try: int("aaa") print("---aaa---") except: print("出现异常-->英文字母不能转换为数字") print("----------") # 输出结果 出现异常-->英文字母不能转换为数字 ----------
②. Multi-branch exceptions. When we need to catch different exceptions, we can use multiple excepts to achieve this. If you need to obtain exception information, you can get the exception object through the as variable name, such as line 7
try: nu = int("100") print("转换后的值nu:", nu) i = 1 / 0 except ValueError: print("出现异常-->英文字母不能转换为数字") except ZeroDivisionError as e: # 通过 as 变量名 获取异常的对象 print("出现异常-->除数不能为零") print("异常的提示信息-->", e) except: pass print("----------") # 输出结果 转换后的值nu: 100 出现异常-->除数不能为零 异常的提示信息--> division by zero ----------
③ When we need to press multiple exceptions with the same The processing method can be used except (ValueError, [ZeropisionError [, NameError]]):
try: i = 1 / 0 nu = int("aa") except (ValueError, ZeroDivisionError) as e: print(e) except: pass print("----------") # 输出结果 division by zero ----------
2) try-except-else-finally statement
① When the finally statement appears in try-except-else-finally, the statement in the finally statement block will be executed regardless of whether an exception occurs, while the statement in the else statement will only be executed if no exception occurs
When an exception occurs, try-except-else-finally is as follows
try: i = 1 / 0 print("没有出现异常i值", i) except Exception as e: print("出现异常-->", e) else: print("没有出现异常-->执行else") finally: print("不管是否出现异常,这里的语句一定会被执行") # 输出结果 出现异常--> division by zero 不管是否出现异常,这里的语句一定会被执行
When no exception occurs, try-except-else-finally is as follows
try: i = 1 / 1 print("没有出现异常i值", i) except Exception as e: print("出现异常-->", e) else: print("没有出现异常-->执行else") finally: print("不管是否出现异常,这里的语句一定会被执行") # 输出结果 没有出现异常i值 1.0 没有出现异常-->执行else 不管是否出现异常,这里的语句一定会被执行
②. try-except-else-finally can also be used separately. There are three forms: 1) try-except-finally 2) try-except-else 3) try-finally. The code will not be shown here
4. Exception delivery
If there is no statement to handle the exception in the statement where the exception occurs, the exception will be raised. Pass through layers until a statement that handles an exception is encountered, or the python interpreter terminates the program
def test2(): int("aa") def test1(): test2() try: test1() except Exception as e: print(e) print("-----------") # 输出结果 invalid literal for int() with base 10: 'aa' -----------
As above, if an exception occurs in line 2 of test2, it will be passed to line 5 It is passed at the statement that calls test2. There is still no exception handling statement here. It will continue to be passed to the upper layer and is caught by except at line 8.
5. Throw an exception raise
1) Throw an exception defined by python
You can throw an exception by raising the exception type, and the thrown exception will also be caught by except. As shown below, line 4
age = 500 try: if age < 0 or age > 200: raise ValueError("age范围0-200") print("age", age) except ValueError as e: print("出现异常-->", e) # 输出结果 出现异常--> age范围0-200
2) throws a custom exception
抛出自定义异常首先得有个自定义的异常类,注:自定义的异常必须直接或间接的继承Exception基类
class MyException(Exception): # 自定义异常类 def __init__(self, msg): self.msg = msg age = 500 try: if age < 0 or age > 200: raise MyException("age范围0-200") # 抛出自定义异常 print("age", age) except MyException as e: print("出现异常-->", e) # 输出结果 出现异常--> age范围0-200
当然自定义异常类也可以拥有许多的功能,就得看需求添加啦
6、在异常处理中抛出异常
有某需求:当捕获到异常时处理完后想继续抛出异常.....
在except中用raise可以抛出当前异常
try: i = 1 / 0 # 异常的语句 except Exception as e: print("出现异常-->", e) raise # 处理完后继续抛出异常,raise表示抛出当前异常 print("-------------") # 输出结果 出现异常--> division by zero Traceback (most recent call last): File "<stdin>", line 2, in <module> i = 1 / 0 ZeroDivisionError: division by zero
The above is the detailed content of What are the exceptions in python? Detailed introduction to exceptions in python. For more information, please follow other related articles on the PHP Chinese website!