


Exception
In Python
, the exception object (exception object)
is used to represent the abnormal situation that occurs during the execution of the code. When the executing program explodes In case of error, an exception will be thrown.
If the exception is not handled correctly, the operation will be terminated.
You can imagine that if you are developing a product and an exception occurs and you do not report the cause of the exception, it will be very uncomfortable and it will be difficult to solve the abnormal problem.
In order to improve the stability and flexibility of the product, Python
runs developers to capture and handle various exceptions. General internal module errors such as KeyError exception class
are more common , of course there are many others.
Errors and exceptions
For a brief understanding, Python divides code execution errors into two categories: syntax error(syntax error)
and exception(exception)
.
Grammar Error
First of all, there is the problem of grammatical errors. It can be seen from the words that the code parsing error is wrong.
This kind of error usually occurs among beginners. The main reason is that the code being executed does not comply with the Python syntax specifications, so a syntax error will be reported and the code will stop.
An error example is given below:
>>> if for not in list(1,2,3,4) File "<stdin>", line 1 if for not in list(1,2,3,4) ^ SyntaxError: invalid syntax</stdin>
From the above error report, we can know that it is a syntax error and invalid syntax. And pointed out that the error is in the position of for
. Obviously if
and for
cannot be used together.
Exception
Exception is an error found during the execution of the code. It is difficult to detect in advance. Even if the code is written in a very standard way, execution exceptions may occur. Condition.
An error example is given below. In mathematical operations, a frequently discussed problem is the case of dividing by zero. However, 0 is not allowed as a divisor because it would cause an exception.
>>> a = 5 / 0 Traceback (most recent call last): File "<stdin>", line 1, in <module> ZeroDivisionError: division by zero</module></stdin>
Obviously the error message indicates that 0 is incorrect as the divisor.
Exception handling
After we understand errors and exceptions, we have to handle exceptions. Problems like syntax errors can be avoided by practicing more. For the second exception, python
gives a try-except
statement to handle it.
For a clearer explanation, let’s take the above situation where the divisor is 0 as an example. We capture and handle exceptions by adding a try-except
statement:
def division(x, y): try: return x / y except ZeroDivisionError: print("0不能作为除数!!!")
Then we try calling the function in the terminal:
division(x=1, y=0)
Output:
0 cannot be used as a divisor! ! !
Although our input is wrong and theoretically should report an error, no error was reported and a paragraph was returned.
The following explains how the try-except
statement works:
The code in Try-except will be executed normally
If no exception occurs, skip the except code block and end try-except
If a problem exception occurs in a certain line of code in try-except, the remaining code Stop execution. If the exception that occurs is consistent with what is specified in except, the code block in except is executed. The exception handling ends and the entire application continues to execute.
#If the exception that occurs is consistent with what is specified in except. does not match, then the try statement will be jumped out, the program will continue to throw exceptions and terminate the execution of the code
Of course, the code we write may have a variety of exceptions, so we can All exceptions are written in an except statement block, and the specific implementation is as follows:
except (RuntimeError, TypeError, NameError):pass
If any exception expression in the exception list is captured, it will enter except
processing.
Of course, if you want to handle each exception individually, you can also handle it one by one:
def passpass(x=1): try: return print(x+x) except (RuntimeError, TypeError, NameError): pass except TypeError: print('参数错误啦~') except NameError: print('名称错误啦~')
I’ll update here today and go skipping rope tomorrow. , Hey, roll rolls every day, old Beijing chicken rolls ~ (2022.4.20)
Python’s exception types can be inherited. We only need to know here that if the exception type is specified after except Exceptions inherit from previous exceptions, so subsequent exceptions will also be caught. The example is as follows:
class A(Exception): pass class B(A): pass class C(B): pass for cls in [A, B, C]: try: raise cls() except C: print('C') except B: print('B') except A: print('A')
will output:
A
B
C
On the contrary, if the order of except is reversed, only A will be output. Since exceptions B and C both inherit from A, it will terminate after catching the B exception:
class A(Exception): pass class B(A): pass class C(B): pass for cls in [A, B, C]: try: raise cls() except A: print('A') except B: print('B') except C: print('C')
The output is all A:
A
A
A
If all the exceptions are extracted one by one, it will be very troublesome. At this time, you can If the exception type is not set in an except, all remaining uncaught exceptions will be caught:
def passpass(x=1): try: return print(x/x) except TypeError: print('参数错误啦~') except NameError: print('名称错误啦~') except: print('报错啦~自己查')
An important function: else.
The else statement is used to perform some additional operations , for example, some file operations are performed in the try code block, and resources can be released in else. The syntax format of else is as follows:
try: pass except: pass else: pass
Of course, we can also operate exceptions, as follows:
def passpass(x=1): try: return print(x/x) except TypeError as error: print('参数错误啦~', error) except NameError: print('名称错误啦~') except: print('报错啦~自己查')
Throw independently Exception
In some normal situations, developers do not make execution errors, but it does not comply with the design logic. Therefore, developers need to actively throw exceptions. At this time, we need to use the raise statement to throw exceptions:
>>> raise NameError('HiThere') Traceback (most recent call last): File "<stdin>", line 1, in <module> NameError: HiThere</module></stdin>
Customized exceptions
When Python’s built-in exceptions cannot meet development needs, you can customize exceptions.
自定义异常类必须要直接或间接继承自Exception类。尽管自定义异常类与其他类具有相同的功能,但为保持简洁,应该仅提高必要的属性。
class Error(Exception): """Base class for exception in this module.""" pass class InputError(Error): """Exception raised for errors in the input. Attributes: expression -- input expression in which the error occurred message -- explanation of the winerror """ def __init__(self, expression, message): self.expression = expression self.message = message
finally子句
else在代码正常执行后才会被执行的代码块,但有些情况无论代码块是否出现异常都要执行,则需要用到finally语句:
def passpass(x=1): try: return print(x/x) except TypeError as error: print('参数错误啦~', error) except NameError: print('名称错误啦~') except: print('报错啦~自己查') finally: print('运算结束~')
The above is the detailed content of What is the method of exception handling in Python basic tutorial?. For more information, please follow other related articles on the PHP Chinese website!

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.

Python's real-world applications include data analytics, web development, artificial intelligence and automation. 1) In data analysis, Python uses Pandas and Matplotlib to process and visualize data. 2) In web development, Django and Flask frameworks simplify the creation of web applications. 3) In the field of artificial intelligence, TensorFlow and PyTorch are used to build and train models. 4) In terms of automation, Python scripts can be used for tasks such as copying files.

Python is widely used in data science, web development and automation scripting fields. 1) In data science, Python simplifies data processing and analysis through libraries such as NumPy and Pandas. 2) In web development, the Django and Flask frameworks enable developers to quickly build applications. 3) In automated scripts, Python's simplicity and standard library make it ideal.

Python's flexibility is reflected in multi-paradigm support and dynamic type systems, while ease of use comes from a simple syntax and rich standard library. 1. Flexibility: Supports object-oriented, functional and procedural programming, and dynamic type systems improve development efficiency. 2. Ease of use: The grammar is close to natural language, the standard library covers a wide range of functions, and simplifies the development process.

Python is highly favored for its simplicity and power, suitable for all needs from beginners to advanced developers. Its versatility is reflected in: 1) Easy to learn and use, simple syntax; 2) Rich libraries and frameworks, such as NumPy, Pandas, etc.; 3) Cross-platform support, which can be run on a variety of operating systems; 4) Suitable for scripting and automation tasks to improve work efficiency.

Yes, learn Python in two hours a day. 1. Develop a reasonable study plan, 2. Select the right learning resources, 3. Consolidate the knowledge learned through practice. These steps can help you master Python in a short time.


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

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

Safe Exam Browser
Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

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