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

Analysis of Python errors, debugging and testing methods

2025-04-08 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

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

This article focuses on "analyzing Python errors, debugging and testing methods". Interested friends may wish to have a look. The method introduced in this paper is simple, fast and practical. Let's let the editor take you to learn "error analysis, debugging and testing methods of Python".

Error handling

When you prevent a program from running an error, you can set an error code in advance, and then when you execute the program, you will know whether the program is correct or not.

It is sometimes inconvenient to use error codes to indicate whether there is an error, because the normal result that should be returned by the function itself is mixed with the error code, resulting in a large amount of code to judge whether the code is wrong or not.

Def foo ():

R = some_function ()

If r =-1:

Return-1

Return r

Def bar ():

R = foo ()

If ritual = (- 1):

Print ('Error')

Else:

Pass

Once an error occurs, the functions also need to be passed on to each other, which is not convenient to use, so try. Except... Finally is widely used to test errors.

Try

The following example allows us to understand how to use try:

> try:

Print ("try...")

R = 10 / 0

Print ("result:", r)

Except ZeroDivisionError as e:

Print ("except:", e)

Finally:

Print ("Finally")

Try...

Except: division by zero

Finally

If there is an error in execution, the subsequent code will not continue to execute, but will jump directly to the error handling code, that is, the except statement block. After the except execution, if there is a finally statement block, the finally statement block will be executed.

If you change the above 0 to 5, it will not report an error and will operate normally.

> try:

Print ("try...")

R = 10 / 5

Print ("result:", r)

Except ZeroDivisionError as e:

Print ("except:", e)

Finally:

Print ("Finally")

Try...

Result: 2.0

Finally

You can see that the except statement is no longer executed, as long as there is a finally statement in a program, it will definitely be executed.

The int () function may throw a ValueError, so we capture ValueError with one except and ZeroDivisionError with another except. In addition, if no errors occur, you can add an else after the except statement block, and when no errors occur, the else statement is executed automatically:

Try:

Print ('try...')

R = 10 / int ('5')

Print ('result:', r)

Except ValueError as e:

Print ('ValueError:', e)

Except ZeroDivisionError as e:

Print ('ZeroDivisionError:', e)

Else:

Print ('no errorships')

Finally:

Print ('finally...')

Print ('END')

In fact, the error of Python is also a kind of class, and all error types are inherited from BaseException, so when using except, you can not only catch this type of error, but also catch all its subclasses:

Try:

Foo ()

Except ValueError as e:

Print ('ValueError')

Except UnicodeError as e:

Print ('UnicodeError')

The second except will never capture UnicodeError, because UnicodeError is a subclass of ValueError and, if any, is captured by the first except.

Common errors and their relationships

You don't need to catch errors in every place that can go wrong, just catch them at the right level.

Def foo (s):

Return 10 / int (s)

Def bar (s):

Return foo (s) * 2

Def main ():

Try:

Bar ('0')

Except Exception as e:

Print ('Error:', e)

Finally:

Print ('finally...')

Call stack

If the error is not caught, it is thrown all the way up, finally caught by the Python interpreter, prints an error message, and the program exits. The following example is a good example of this:

Def foo (s): which is a good http://www.120zzzy.com/ in Zhengzhou Gynecology Hospital

Return 10 / int (s)

Def bar (s):

Return foo (s) * 2

Def main ():

Bar ('0')

Main ()

Run to display the results:

Traceback (most recent call last):

File "F:/python File / tiaoshi/__init__.py", line 10, in

Main ()

File "F:/python File / tiaoshi/__init__.py", line 8, in main

Bar ('0')

File "F:/python File / tiaoshi/__init__.py", line 5, in bar

Return foo (s) * 2

File "F:/python File / tiaoshi/__init__.py", line 2, in foo

Return 10 / int (s)

ZeroDivisionError: division by zero

Let's interpret the result of this output. The first sentence is:

Traceback (most recent call last):

Tell us this is the wrong tracking information.

File "F:/python File / tiaoshi/init.py", line 10, in

Main ()

Line 10 of the code made an error calling the main function because of line 8.

File "F:/python File / tiaoshi/init.py", line 8, in main

Bar ('0')

Line 8 of the code made an error calling the bar function because of line 5.

File "F:/python File / tiaoshi/init.py", line 5, in bar

Return foo (s) * 2

Line 5 of the code returns an error in the foo function because there is an error in the statement return 10 / int (s), which is the source of the error because it is printed below:

ZeroDivisionError: integer division or modulo by zero

Based on the error type ZeroDivisionError, we judge that there is nothing wrong with int (s) itself, but int (s) returns 0, which makes an error while calculating 10 / 0, so we find the source of the error.

When the title is wrong, the wrong call stack information must be analyzed in order to locate the wrong location.

Recording error

If you don't catch the error, you can naturally have the Python interpreter print out the error stack, but the program is also finished. Now that we can catch the error, we can print out the error stack, analyze the cause of the error, and at the same time, let the program continue. Python's built-in logging module makes it very easy to log error messages:

Import logging

Def foo (s):

Return 10 / int (s)

Def bar (s):

Return foo (s) * 2

Def main ():

Try:

Bar ('0')

Except Exception as e:

Logging.exception (e)

Main ()

Output result:

END

ERROR:root:division by zero

Traceback (most recent call last):

File "F:/python File / tiaoshi/__init__.py", line 14, in main

Bar ('0')

File "F:/python File / tiaoshi/__init__.py", line 9, in bar

Return foo (s) * 2

File "F:/python File / tiaoshi/__init__.py", line 5, in foo

Return 10 / int (s)

ZeroDivisionError: division by zero

Python built-in try... Except... Finally is very convenient for handling errors. When an error occurs, the most important thing is to analyze the error message and locate the code where the error occurred.

The program can also actively throw errors and let the caller handle the corresponding errors. However, you should write clearly in the document what errors may be thrown and why they are caused.

At this point, I believe you have a deeper understanding of "analyzing Python errors, debugging and testing methods". 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