前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >[005] Python异常处理三板斧——Try, Except, and Assert!

[005] Python异常处理三板斧——Try, Except, and Assert!

作者头像
Sam Gor
发布2020-11-19 15:31:52
8170
发布2020-11-19 15:31:52
举报
文章被收录于专栏:SAMshare

“在我们写Python脚本的时候,总是会幻想着一步到位,代码如丝滑般流畅运行,这就需要我们预先考虑各种场景,然后对可能会出现的问题进行预先处理,而识别与处理各类问题(异常),常用的就是标题所说的——Try,Except,and Assert。本文针对这三个关键词,举了一系列的栗子,可以具体来看看。

The dream of every software programmer is to write a program that runs smoothly. However, this is not usually the case at first. The execution of a code stops in case of an error.

Unexpected situations or conditions might cause errors. Python considers these situations as exceptions and raises different kinds of errors depending on the type of exception.

ValueError, TypeError, AttributeError, and SyntaxError are some examples for those exceptions. The good thing is that Python also provides ways to handle the exceptions.

Consider the following code that asks the user to input a number and prints the square of the number.

代码语言:javascript
复制
a = int(input("Please enter a number: "))
print(f'{a} squared is {a*a}')

It works fine as long as the input is a number. However, if the user inputs a string, python will raise a ValueError:

We can implement a try-except block in our code to handle this exception better. For instance, we can return a simpler error message to the users or ask them for another input.

代码语言:javascript
复制
try:
   a = int(input("Please enter a number: "))
   print(f'{a} squared is {a*a}')
except:
   print("Wrong input type! You must enter a number!")

In the case above, the code informs the user about the error more clearly.

If an exception is raised due to the code in the try block, the execution continues with the statements in the except block. So, it is up to the programmer how to handle the exception.

The plain try-except block will catch any type of error. But, we can be more specific. For instance, we may be interested in only a particular type of error or want to handle different types of error differently.

The type of error can be specified with the except statement. Consider the following code that asks user for a number from a list. Then, it returns a name from a dictionary based on the input.

代码语言:javascript
复制
dict_a = {1:'Max', 2:'Ashley', 3:'John'}
number = int(input(f'Pick a number from the list: {list(dict_a.keys())}'))

If the user enters a number that is not in the given list, we will get a KeyError. If the input is not a number, we will get a ValueError. We can handle both cases using two except statements.

代码语言:javascript
复制
try:
   dict_a = {1:'Max', 2:'Ashley', 3:'John'}
   number = int(input(f'Pick a number from the list: 
   {list(dict_a.keys())}'))
   print(dict_a[number])
except KeyError:
   print(f'{number} is not in the list')
except ValueError:
   print('You must enter a number!')

Python also allows raising your own exception. It is kind of customizing the default exceptions. The raise keyword along with the error type is used to create your own exception.

代码语言:javascript
复制
try:
   a = int(input("Please enter a number: "))
   print(f'{a} squared is {a*a}')
except:
   raise ValueError("You must enter a number!")

Here is the error message in case of a non-number input.

代码语言:javascript
复制
ValueError: You must enter a number!

Let’s do another example that shows how to use try-except block in a function.

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

代码语言:javascript
复制
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 a ZeroDivisionError because the length of an empty list is zero.

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

代码语言:javascript
复制
def avg_value(lst):
   try:
      avg = sum(lst) / len(lst)
      return avg
   except:
      print('Warning: Empty list')
      return 0

In case of empty lists, the function will print a warning and return 0.

代码语言:javascript
复制
a = []
print(avg_value(a))

#Warning: Empty list
#0

The try and except blocks are used to handle exceptions. The assert is used to ensure the conditions are compatible with the requirements of a function.

If the assert is false, the function does not continue. Thus, the assert can be an example of defensive programming. The programmer is making sure that everything is as expected.

Let’s implement the assert in our avg_value function. We must ensure the list is not empty.

代码语言:javascript
复制
def avg_value(lst):
   assert not len(lst) == 0, 'No values'
   avg = sum(lst) / len(lst)
   return avg

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

If the condition in the assert statement is false, an AssertionError will be raised:

代码语言:javascript
复制
a = []
print(avg_value(a))
AssertionError: No values

The assert is pretty useful to find bugs in the code. Thus, they can be used to support testing.

Conclusion

We have covered how try, except, and assert can be implemented in the code. They all come in handy in many cases because it is very likely to encounter situations that do not meet the expectations.

Try, except, and assert provides the programmer with more control and supervision over the code. They spot and handle exceptions very well.

Thank you for reading. Please let me know if you have any feedback.

本文参与 腾讯云自媒体同步曝光计划,分享自微信公众号。
原始发表:2020-11-16,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 SAMshare 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • Conclusion
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档