


What are the exceptions in python? Detailed introduction to exceptions in python
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!

Python is easier to learn and use, while C is more powerful but complex. 1. Python syntax is concise and suitable for beginners. Dynamic typing and automatic memory management make it easy to use, but may cause runtime errors. 2.C provides low-level control and advanced features, suitable for high-performance applications, but has a high learning threshold and requires manual memory and type safety management.

Python and C have significant differences in memory management and control. 1. Python uses automatic memory management, based on reference counting and garbage collection, simplifying the work of programmers. 2.C requires manual management of memory, providing more control but increasing complexity and error risk. Which language to choose should be based on project requirements and team technology stack.

Python's applications in scientific computing include data analysis, machine learning, numerical simulation and visualization. 1.Numpy provides efficient multi-dimensional arrays and mathematical functions. 2. SciPy extends Numpy functionality and provides optimization and linear algebra tools. 3. Pandas is used for data processing and analysis. 4.Matplotlib is used to generate various graphs and visual results.

Whether to choose Python or C depends on project requirements: 1) Python is suitable for rapid development, data science, and scripting because of its concise syntax and rich libraries; 2) C is suitable for scenarios that require high performance and underlying control, such as system programming and game development, because of its compilation and manual memory management.

Python is widely used in data science and machine learning, mainly relying on its simplicity and a powerful library ecosystem. 1) Pandas is used for data processing and analysis, 2) Numpy provides efficient numerical calculations, and 3) Scikit-learn is used for machine learning model construction and optimization, these libraries make Python an ideal tool for data science and machine learning.

Is it enough to learn Python for two hours a day? It depends on your goals and learning methods. 1) Develop a clear learning plan, 2) Select appropriate learning resources and methods, 3) Practice and review and consolidate hands-on practice and review and consolidate, and you can gradually master the basic knowledge and advanced functions of Python during this period.

Key applications of Python in web development include the use of Django and Flask frameworks, API development, data analysis and visualization, machine learning and AI, and performance optimization. 1. Django and Flask framework: Django is suitable for rapid development of complex applications, and Flask is suitable for small or highly customized projects. 2. API development: Use Flask or DjangoRESTFramework to build RESTfulAPI. 3. Data analysis and visualization: Use Python to process data and display it through the web interface. 4. Machine Learning and AI: Python is used to build intelligent web applications. 5. Performance optimization: optimized through asynchronous programming, caching and code

Python is better than C in development efficiency, but C is higher in execution performance. 1. Python's concise syntax and rich libraries improve development efficiency. 2.C's compilation-type characteristics and hardware control improve execution performance. When making a choice, you need to weigh the development speed and execution efficiency based on project needs.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

VSCode Windows 64-bit Download
A free and powerful IDE editor launched by Microsoft

EditPlus Chinese cracked version
Small size, syntax highlighting, does not support code prompt function

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

SublimeText3 Chinese version
Chinese version, very easy to use