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

An example Analysis of Python exception handling method

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

Share

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

This article mainly introduces the relevant knowledge of Python exception handling method case analysis, the content is detailed and easy to understand, the operation is simple and fast, and has a certain reference value. I believe you will gain something after reading this article on method case analysis of Python exception handling. Let's take a look.

What is exception and exception handling

Exception-> can be understood as unusual.

Under normal circumstances, our program is executed line by line from the top down, and the execution of the program will not be terminated until the last line. And abnormal circumstances will cause our program to give up halfway and stop execution. In general, the stop of execution is caused by the error of our program, and the exception is the error, which will cause our program to crash and stop running. This is very unfriendly in our work!

Throughout the life of the program, there is no guarantee that the program will not go wrong. So when errors are encountered, in order not to affect the execution of the program, we need to handle these exceptions. The exception mechanism in Python can monitor and catch exceptions. When there is an error in the program, the exception can be handled temporarily and properly, which can make the program continue to run normally.

Summary:

The essence of exception is error.

The occurrence of an exception will cause the program to crash and stop execution

Monitor the exception and catch it, and properly handle the program that caused the exception, so that the program can continue to run normally.

Next, let's take a quick look at the syntax of how to catch exceptions and handle them.

Exception syntax try: # exception keyword, meaning of attempt # Business code block checked and protected by the try keyword except: # the handling keyword after the exception is found will be followed by an error type (exception type). The exception type can be left empty after the error occurs in the code block of # try The code block of except will be executed # this is usually the remediation logic when there is an error in the try code block

Let's look at a simple example:

1 / 0 # We all know that 0 cannot be divisible, so the following error report # > execution result is as follows # > > ZeroDivisionError: division by zero # > our code error report is called exception throw. This error message tells us why the error is reported and the business will be stopped at the same time. In the program, we are allowed to make mistakes, but we need to catch the exceptions that may be encountered. # > carry on reasonable handling, so that the program can run reasonably when it encounters an exception.

Take a look at the catch for the exception in the example above

Try: 1 / 0except: print ('Note: 0 is not divisible by 1') print ('ZeroDivisionError: division by zero has been captured, the program continues to execute') # > the execution result is as follows # > > Note: 0 is not divisible by 1 # > ZeroDivisionError: division by zero has been captured, and the program continues to execute # > > although the try code block throws an exception, we make reasonable circumvention through except to make our program continue to execute downwards.

Next, let's use the upper () function that we learned before to do a small case:

Define a upper, using the upper () function. Uppercase the incoming string, if the passed-in parameter is not a string, catch the exception and handle it.

Def upper (str_data): new_str = None try: new_str = str_data.upper () except: print ('upper () function failed to convert characters to uppercase!' , 'return result is:', new_str) return new_strresult = upper ('test') print (' input parameter return value is:', result) # > > execution result is as follows: # > input parameter return value is: TESTresult = upper (1) print (result) # > execution result is as follows: # > upper () function failed to convert characters in uppercase! The returned result is: None catches a common exception

We just passed try... Except... The exception was caught and handled properly, but we don't know what caused the error. So we have to get the type of exception. First, let's learn how to get the general exception type, which is a catch method that we use when we can't be sure what kind of exception it is.

The usage is as follows:

Try: except Exception as e: # convert the error cause of the general exception to the variable e, and as as the keyword # can also be understood as giving the Exception general exception type an alias e # e variable name can be given any name Generally speaking, it is customary to use e as the variable name of exception catch # e is the abbreviation of error

Examples of generic exception traps are as follows:

Def upper (str_data): new_str = None try: new_str = str_data.upper () except Exception as e: print ('upper () function failed to convert characters to uppercase!' , 'return result is: {}' .format (e) return new_strresult = upper (1) print (result) # > the execution result is as follows: # > upper () function failed to convert characters to uppercase! The returned result is: 'int' object has no attribute' upper' catches a specific exception

Catching a specific exception is how we can determine which specific type of exception will occur in the code block of try and catch it. Syntax is the same as general exceptions, just write specific exception types in the exception type area.

Let's take ZeroDivisionError: division by zero as an example.

Try: 1 / 0except ZeroDivisionError as e: # write the specified exception type: ZeroDivisionError # ZeroDivisionError is a specific exception built into Python: 0 cannot be divisible print (e) # > the execution result is as follows: # > division by zero

Section: think about a question, do we use general exceptions or specific exceptions at work?

From a convenient point of view, it is easier to use generic exceptions. The development cost is low, and there is no need to care about the specific type of exception. In fact, Exception does not know which type of exception is specific. It needs to go to the vast exception database to find it and throw it accordingly. Although it is not as fast as specified exception handling, the processing speed is also imperceptible.

If we can know the specific exception types that might occur in the try code block, we still want to use the specific exception types. This can accurately correspond to errors.

It should be noted that when the specific exception type we specified does not appear in our try code block, the code execution will still report an error. So each has its own advantages and disadvantages and can be used according to the specific circumstances of our business.

How to catch multiple exceptions

In our usual development work, there are likely to be multiple exception types in the same code block. So how do we support the capture of multiple exceptions?

In fact, exception capture is very flexible, but also supports multiple exception catch methods.

Catch multiple exceptions-method 1try: result = 1 / 0except ZeroDivisionError as E1: print (E1) except Exception as e2: # you can use multiple except to catch multiple exceptions print ('this is a public except, bug is% s'% e2) # > it is important to note that when there are multiple exceptions in the except code block, when the first exception is caught, it will not be caught further.

It is important to note that when there are multiple exceptions in the except code block, when the first exception is caught, it will not be caught further.

Catch multiple exceptions-method 2try: result = 1 / 0except (ZeroDivisionError, Exception) as e: # define multiple exception types in parentheses after except (parentheses are actually tuples) # when except wraps multiple exception types with tuples, print (e) is thrown as the exception type is caught

Examples are as follows:

Def test (): try: print (name) # because the variable name does not exist, a NameError: name' name' is not defined exception # attempts to catch a NameError exception except (ZeroDivisionError, NameError) as e: print (e) print (type (e)) test () # > > the execution result is as follows: # > > name' name' is not defined# >

The second is the more commonly used method of catching exceptions.

This is the end of the article on "method example Analysis of Python exception handling". Thank you for reading! I believe you all have a certain understanding of the knowledge of "case analysis of Python exception handling methods". If you want to learn more knowledge, you are welcome to follow the industry information channel.

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