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

本文介绍了Python中处理异常的重要工具Try, Except和Assert。通过实例展示了如何使用它们来优雅地处理错误,如ValueError、KeyError等。当输入类型错误或列表中不存在的键时,利用try-except块给出清晰的错误提示。同时,通过raise自定义异常,并在函数中使用try-except来避免运行时错误。最后,assert用于确保函数的输入符合预期,辅助调试代码。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

在我们写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.

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.

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.

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.

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.

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.

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.

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.

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.

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.

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:

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.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值