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

How to avoid abusing try...except in Python

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 "how to avoid abuse of try...except in Python". The content of the explanation is simple and clear, easy to learn and understand. Please follow the editor's train of thought to study and learn "how to avoid abuse of try...except in Python".

Many people like to use try...except Exception when writing Python code, or even one layer at a time, whether it is useful or not.

Hongmeng official strategic cooperation to build-- HarmonyOS technology community ss= "dp-xml" > ss= "alt" > def func (): ss= "" > try: ss= "alt" > "function internal code" ss= "> except Exception as e: ss=" alt "> print ('function error:' E) ss= "" > ss= "alt" > ss= "" > try: ss= "alt" > func () ss= "" > except Exception as e: ss= "alt" > print ('function error:', e)

No matter whether it is necessary or not, I put on try...except... anyway. There is sense of security.

After there were too many doll condoms in Russia, the nightmare began. Let's take a look at the following error report:

Why don't you tell me, which function is wrong?

If you are suffering from abuse of try...except... Here are three ways to get you out of your misery.

Expose the problem

In the early stages of program development, do not use try...except.... Let Python expose the problem. Through the error report of Python, you can directly see which line of code has a problem and what is the problem.

Even sometimes, not only do you not need to catch an exception, you should also take the initiative to throw an exception. After the completion of the project, if you are doing a third-party library for others to call, then you should throw more exceptions instead of returning a common error message without authorization.

For example, you want to implement a function: query_name, which takes a numeric id as the argument and outputs the user name. You might write like this:

Hongmeng official strategic cooperation to build-- HarmonyOS technology community ss= "dp-xml" > ss= "alt" > def query_name (user_id): ss= "" > if not isinstance (user_id, int): ss= "alt" > return {'success': False,' msg': 'user id must be integer'} ss= "" >.

But in practice, it would be better to throw an exception directly:

Hongmeng official strategic cooperation to build-- HarmonyOS technology community ss= "dp-xml" > ss= "alt" > def query_name (user_id): ss= "> if not isinstance (user_id, int): ss=" alt "> raise Exception ('user id must be integer'} ss=">.

Even in some cases, you can use Python's assertion:

Hongmeng official strategic cooperation to build-- HarmonyOS technology community ss= "dp-xml" > ss= "alt" > def query_name (user_id): ss= "" > assert isinstance (user_id, int), 'user id must be integer' ss= "alt" >.

As shown in the following figure:

As long as user_id is not an integer, AssertionError is thrown.

These assertion statements work properly when we execute python3 xxx.py directly. But we can invalidate all assert xxx statements through python3-o xxx.py.

Only by exposing anomalies as early as possible can the problem be solved earlier.

Catch specific exceptions instead of all exceptions

Catch only exceptions that you clearly know. You know why these anomalies occur, and you know how to solve them.

For example, we use requests to request a website, and sometimes we may request a timeout due to network problems. Once timeout occurs, requests throws a timeout exception, as shown in the following figure:

In this case, you know that a Timeout exception may occur in this place, and you know that when it occurs, just try again. So, you can catch this exception:

Notice that in this place, requests executes the .json () method. If the content returned by URL may not be a string in JSON format, JSONDecodeError will be reported here, as shown below:

If you don't make a distinction and just use except Exception, how do you know if it's a timeout problem that you can handle normally, or an exception returned by website content that you can't handle properly?

So, catch only exceptions that you know why it happened and you know how to handle it. Throw an exception that you can't anticipate or handle. Don't capture without authorization.

Forcibly print error message

If you have to use try...except Exception if you really have to, how can you print out the location of the error? In fact, there is a way. That is to use the traceback module that comes with Python.

Its use is very simple:

Hongmeng official strategic cooperation and co-construction-- HarmonyOS technology community ss= "dp-xml" > ss= "alt" > import traceback ss= "> ss=" alt "> try: ss=" > 1 + 'a'ss= "alt" > except Exception: ss= "> print (traceback.format_exc ())

The running effect is shown in the following figure:

The number of lines in which the exception is located and the specific error type are printed successfully. Obviously, you need to write a lot of code for no reason.

Thank you for reading, the above is the content of "how to avoid abuse of try...except in Python". After the study of this article, I believe you have a deeper understanding of how to avoid abuse of try...except in Python, and the specific use needs to be verified in practice. Here is, the editor will push for you more related knowledge points of the article, welcome to follow!

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