Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

What are the knowledge points of Python exception handling

2025-01-17 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

This article mainly explains "what are the knowledge points of Python exception handling". Interested friends may wish to take a look. The method introduced in this paper is simple, fast and practical. Next let the editor to take you to learn "what are the knowledge points of Python exception handling"?

Exception capture

First of all, let's look at an example:

I asked the Python interpreter to give me an exception through print (a), which contains all the context information for the error message, the code path, the error code content, the error message, and so on.

The reason for the error in the statement print (a) is that the variable an is not defined (NameError: name'a'is not defined), which is clear before I write the code.

However, in the actual programming process, with the increase of the amount of code, we are sometimes not sure whether a variable has been assigned successfully, if the variable has not been successfully assigned, the program may report an error directly when it operates on it as planned.

There are two ways to solve this problem:

Check whether the value of a variable already exists before operating on it (such as addition and subtraction), and if not, tell the user

Catch the exception and tell the user

In fact, the result of these two methods is to tell the user an error message, and there is not much change in the result. Today we will mainly talk about the second way, which is to catch exceptions automatically.

Now let's modify the code to catch the exception and customize the handling:

The above code example shows that we caught the error through the syntax of exception catching try except and customized its output.

Let's explain this code:

Try is used to define a syntax block for exception catch.

In the try indented block, we can write the code we want to implement normally.

In the except block, we define the code to be executed if the program reports an error, which in this case prints the error message directly (name'a'is not defined).

The use of Exception as e after except is to define the error message type (Exception) and to assign the error message to the variable e.

By using the try.. check syntax anywhere in the code, we can set multiple try...except code blocks. If the program executes normally in try without reporting an error, then the program will skip the except block and execute the code normally.

Exception type

We just used the exception type Exception, which is the base class for regular errors in Python, and can be used if we are not sure about the type of possible error, but it is generally not recommended.

The reason for not using Exception directly is that when we catch an exception, we always want to be able to explicitly report or handle the exception. If all the errors are of Exception type, we don't know exactly where the program went wrong.

Give an example to illustrate this problem.

From the above example, we can learn two things:

Except and try are one-to-many, with one try statement and one or more except statements, which are used to define any exception type and associated handling code

When an exception catch occurs, the program interrupts execution and stays at the first location where the exception reported an error. In this example, because we import xxx actually introduced a module name that does not exist, the program reported an error No module named 'xxx', with the error type ImportError

Now let's try to get rid of import xxx.

Now the program reports a type error (TypeError) because data of type int cannot be added to numbers of type str.

Below I would like to give a list of common exception error types of Python for your reference.

Actively throw an exception

We talked about how Python passively catches exceptions. Now let's talk about how to actively throw exceptions.

Why take the initiative to throw an exception?

Usually the exception we catch through try except is called passive capture, which actually needs to be handled by programmers, such as making some corrections to the contents of the wrong variables to allow them to continue to execute. But taking the initiative to throw an exception usually does not need to be handled, and the programmer has determined that this place must throw an exception to the user and interrupt program execution, so that the programmer no longer has to handle the exception.

Let's look at an example:

In this code, we define an as an integer number.

Then through the instance () internal function to determine an is not a string type of the case, through the raise statement to take the initiative to throw an exception, the error content is also our custom, its function is to directly tell the user that the data is wrong.

A friend will ask a question, your own definition of a = 1, it is clearly an integer number, you also use it to determine whether it is a string, this is not superfluous? Is it a string or not? don't you have a count in mind?

Yes, the reason you have this problem is that our example is too simple, assuming that the content of variable a comes from another module? Or is it from the data that the crawler grabbed from the Internet? At this point, we have no idea what a might be, so we have to use the exception handling mechanism.

The syntax of raise is simple:

Raise [exceptionName [(reason)]]

Just follow it with the type of exception you want to throw, and if it is necessary to write an error, pass it in:

Raise ValueError ("a must be a string")

In addition, the raise statement can also be used in conjunction with try except:

The above example shows how the program actively throws an exception, and then except catches and prints the error message.

Custom exception

In fact, we have just learned that all exception error types are actually a class, so we can also customize an exception class to facilitate use in the program.

Through the above code example:

We have customized an exception class called CustomerError, which inherits from BaseException, the base class of Python exception error type.

Then define its _ _ init__ method and accept the incoming error message with a variable.

You can do nothing in the _ _ init__ method with a pass placeholder, because the CustomerError class inherits from BaseException and is born with all the features of BaseException.

Finally, we throw a CustomerError exception and pass a string content "custom exception" in which the except catches the exception and outputs the exception content.

At this point, I believe you have a deeper understanding of "what are the knowledge points of Python exception handling?" you might as well do it in practice. Here is the website, more related content can enter the relevant channels to inquire, follow us, continue to learn!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report