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

Example Analysis of Python errors and exceptions

2025-02-23 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

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

This article will explain in detail the example analysis of Python errors and exceptions. The editor thinks it is very practical, so I share it for you as a reference. I hope you can get something after reading this article.

Partners who write Python code will inevitably encounter code execution errors and exceptions. This time, let's summarize the errors and exceptions in python in detail and without losing popularity.

Let's start with two questions:

What are Python errors and exceptions?

How to handle Python errors and exceptions?

1. Syntax error

Grammatical errors are probably the most common for beginners, such as the following familiar pictures:

SyntaxError: invalid syntax

Grammatical errors are also called parsing errors, and some brothers will ask what parsing errors are. To put it simply, the basic grammatical structure is miswritten, such as: multitask is written on one line, for loop is not added with': 'and so on. As follows:

Multitask is written in one line

The for loop does not add':'.

As you can see in the above example, for syntax errors, the python parser prints the line of the error and marks an arrow at the location of the error that was first found.

2. Exception

Once you are familiar with python syntax, you can avoid syntax errors, but exceptions often occur in your code (Exception). There are still two questions:

What is the anomaly?

Python uses an exception object (exception object) to represent an exception.

An exception is thrown when an error is encountered. If the exception object is not handled or caught, the program terminates execution with a so-called traceback (an error message).

What's the difference between exceptions and grammatical errors?

Error: means that the code does not conform to the interpreter or compiler syntax

Exception: refers to incomplete, illegal input, or calculation error

With regard to exceptions, for example:

Print ('hello world')

This line of code has an exception because the p of Print should be lowercase:

Python throws the exception type: NameError, that is, the name error.

Examples of other exceptions:

As you can see, there are different types of exceptions, and when an exception occurs, its type name is printed. These are all built-in exceptions in python, and users can also customize the exceptions. I won't repeat them here.

3 、 try...except... Statement

People with experience in python programming will know that try...except... is used in python. Statement to handle exception cases.

Let's take a look at an example of exception handling:

Look, we caught the exception in the program perfectly.

Combined with the above example, the rule for handling exceptions is to put the executed statement in the try code block and the error handler code in the except code block, and except will throw a ZeroDivisionError exception to remind Coder that the error in this code is zero and cannot be divisor.

No exception type can be added after the except, and all exceptions that occur can be caught:

We can put try...except... The principle can be summarized into several main points:

First, execute the try clause (the (multiline) statement between the try and except keywords)

If no exception occurs, skip the except clause and complete the execution of the try statement

If an exception occurs while executing the try clause, the rest of the clause is skipped. Then, if the type of the exception matches the exception after the except keyword, execute the except clause and then continue to execute the code after the try statement

If the exception that occurs does not match the exception specified in the except clause, it is passed to the external try statement; if no handler is found, it is an unhandled exception and execution stops and the message shown above is stopped

4. Multiple except clauses

The try...except... above The statement handles only one exception. What if I want to match several more exception types?

Here we need more than one except clause to help, for example:

Throw an exception ZeroDivisionError

Throw an exception TypeError

Above, we use two except to match the ZeroDivisionError and TypeError exceptions. The first code catches the ZeroDivisionError, and the second code catches the TypeError exception, with no omissions.

Of course, you can also write:

That is, multiple exceptions are caught with a single except, and the exception types are placed in the tuples after the except.

To sum up, for multiple except clauses, it can be summarized as follows:

A try statement may have multiple except clauses to specify different exception handlers

At most one handler will be executed

Handlers only handle exceptions that occur in the corresponding try clause, not those in other handlers within the same try statement

An except clause can name multiple exceptions as tuples with parentheses

5. Try...except Exception as e statement

We often look at the way it is written: try...except Exception as e

What does the e stand for?

Another example:

As you can see from the example, e outputs the exception type.

That is, Exception matches all exceptions and assigns the exception name to e. Of course, it doesn't have to be e, you can take any variable name, it's just a convention to write it that way.

6. Try...except...finally statement

The try...except...finally statement may not be that common, but it is very useful.

Let's say I want to open a txt file with python, then read, write, and finally close the file object. This is a regular process, and if I want to catch exceptions in the code, I have to make sure that I have to close the file regardless of whether there is an exception or not. Finally is used at this point. Take a look at the following example:

The above code catches the exception and finally closes the file object. The role of finaly is that the code behind the finally executes regardless of whether the except catches the exception or not, the try acquires the resources, and the finally releases the resources, ensuring the finishing touches.

7 、 with... Statement

With... Statement is equivalent to the abbreviation of try-finally statement and can replace the function of try-finally.

The expression open ('poem.txt') returns a variable of type _ io.TextIOWrapper assigned to f. You can use this variable to manipulate the file in the with statement block. After executing the with structure, f automatically closes, which is equivalent to bringing a finally.

This is the end of the article on "sample Analysis of Python errors and exceptions". I hope the above content can be helpful to you, so that you can learn more knowledge. if you think the article is good, please share it for more people to see.

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