Get the App
SLTechnology News&Howtos  ›  Internet Technology  › 

Exception Stack tracing and explanation of exception Utilization in python

Shulou Source: shulou.com Published: 2022-06-02 04:58:42 09月15日 Update

This article mainly explains "exception stack tracking and exception utilization explanation in python". Interested friends may wish to take a look. The method introduced in this paper is simple, fast and practical. Let's let Xiaobian take you to learn "exception stack tracking and exception utilization explanation in python"!

I. Tracking of exception stacks

Stack characteristics: first in, then out

Exception throwing, if the inner exception is not handled, then the exception will be slowly passed from the innermost one to the outer one.

If the inner exception has been caught and handled, the inner exception is not passed.

II. Abnormal utilization

When we use the dictionary, there may often be cases where the keywords in the dictionary do not exist, so we will report the error directly. We used to use if statements to determine whether each keyword existed before it was invoked.

Note: Python case is sensitive, pay attention to the call time, case correctness.

1. Determine if key exists

The original way to judge dictionary key values prevents program exceptions

#Call dictionary output, directly use if statement to judge

if "aa" in dic1:

print(dic1["aa"])

else:

print("keyword does not exist")

Use exception catching to simplify code.

try:

print(dic1["aa"])

print(dic1["BB"])

except KeyError:

print("keyword does not exist, throw exception")

2. Determine if a class method exists

Exception utilization of classes, judgment of whether class attributes exist under the old pattern

mc=MyClass()

if(hasattr(MyClass,"abc")):

mc.abc()

else:

print("attribute does not exist")

New type of class attribute call judgment

using exception capture scenarios.

try:

mc.abc()

mc.defd()

except:

print("Property method does not exist")

III. Summary and emphasis

1. Master exception stack tracing.

2. Master the use of exceptions to optimize code and eliminate unknown exceptions.

3. Master the basic form of try catching exceptions.

4. All exceptions thrown after exception capture are exception objects.

At this point, I believe that everyone has a deeper understanding of "exception stack tracking and exception utilization explanation in python". Let's actually operate it! Here is the website, more related content can enter the relevant channels for inquiry, pay attention to us, continue to learn!

Tags: Tracking keys keywords dictionaries attributes methods processing code content situation time statements learning practical new deeper advanced interest size practicality Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Huawei Shulou Tech Info Shulou Information Apple Microsoft