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 deal with Python error exception

2025-01-16 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >

Share

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

This article mainly introduces "how to deal with Python error exception". In daily operation, I believe many people have doubts about how to deal with Python error exception. The editor consulted all kinds of data and sorted out simple and easy-to-use operation methods. I hope it will be helpful to answer the doubt of "how to handle Python error exception". Next, please follow the editor to study!

Every software programmer's dream is to write a program that runs smoothly. However, this was not the case at first. When an error occurs, code execution is stopped.

An unexpected situation or condition may lead to an error. Python treats these conditions as exceptions and throws different types of errors depending on the type of exception.

ValueError,TypeError,AttributeError and SyntaxError are some examples of these exceptions. The good news is that Python also provides ways to handle exceptions.

Consider the following code that requires the user to enter a number and print the number squared.

A = int (input ("Please enter a number:")) print (f'{a} squared is {astata}')

As long as the input is a number, it will work properly. However, if the user enters a string, python throws ValueError:

We can implement the try-except block in our code to better handle this exception. For example, we can return a simpler error message to the user, or ask them to provide other input.

Try: a = int (input ("Please enter a number:")) print (f'{a} squared is {Ayoga}') except: print ("Wrong input type! You must enter a number!")

In these cases, the code will tell the user more clearly about the error.

If an exception is thrown because of code in the try block, execution continues to use the statements in the except block. Therefore, it is up to the programmer to decide how to handle exceptions.

A normal try-except block will catch any type of error. However, we can be more specific. For example, we may only be interested in specific types of errors, or we may want to deal with different types of errors in different ways.

You can use the specify statement to specify the type of error. Consider the following code that asks the user to enter a number from the list. It then returns a name from the dictionary based on the input.

Dict_a = {1 input (f'Pick a number from the list: {list (dict_a.keys ())}'))

If the number entered by the user is not in the given list, we will receive a KeyError. If the input is not a number, we will get ValueError. We can use two except statements to handle both cases.

Try: dict_a = {1 print print is not in the list') except ValueError: print ('You must enter a numbering') number = int (input (f'Pick a number from the list: {list (dict_a.keys ())}')) print (dict_ a) except KeyError: print (f'{number} is not in the list') except ValueError: print ('You must enter a numbered')

Python also allows you to throw your own exceptions. This is one of the custom default exceptions. The raise keyword and error type are used to create your own exceptions.

Try: a = int (input ("Please enter a number:")) print (f'{a} squared is {Ayoga}') except: raise ValueError ("You must enter a number!")

If it is a non-numeric input, this is an error message.

ValueError: You must enter a number!

Let's do another example to show how to use try-except blocks in a function.

The avg_value function returns the average of the list of numbers.

A = [1,2,3] def avg_value (lst): avg = sum (lst) / len (lst) return avgprint (avg_value (a))

If we pass an empty list to this function, it will give ZeroDivisionError because the length of the empty list is zero.

We can implement the try-except block in the function to handle this exception.

Def avg_value (lst): try: avg = sum (lst) / len (lst) return avg except: print ('Warning: Empty list') return 0

If the list is empty, the function displays a warning and returns 0.

A = [] print (avg_value (a)) # Warning: Empty list#0

Try and except blocks are used to handle exceptions. Assertions are used to ensure that conditions are compatible with functional requirements.

If the assertion is false, the function does not continue. Therefore, assertions can be examples of defensive programming. Programmers make sure everything goes as expected.

Let's implement the assertion in the avg_value function. We must make sure that the list is not empty.

Def avg_value (lst): assert not len (lst) = = 0,'No values' avg = sum (lst) / len (lst) return avg

If the length of the list is zero, the function terminates immediately. Otherwise, it will last until the end.

If the condition in the assert statement is false, AssertionError is thrown:

A = [] print (avg_value (a)) AssertionError: No values

Assertions are useful for finding errors in your code. Therefore, they can be used to support testing.

At this point, the study on "how to deal with Python error exception" is over. I hope to be able to solve your doubts. The collocation of theory and practice can better help you learn, go and try it! If you want to continue to learn more related knowledge, please continue to follow the website, the editor will continue to work hard to bring you more practical articles!

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

Internet Technology

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report