Python基础介绍 | Exceptions异常
程序员文章站
2022-04-01 20:40:24
...
今天来讲讲程序中的异常:
出现问题时会引发异常。例如,如果你尝试除以零,ZeroDivisionError则会引发或者如果你尝试访问字典中不存在的键,KeyError则会引发此问题。
empty_dict = {}
# empty_dict['key'] # Uncomment to see the traceback
try-except结构
如果你知道代码块可能以某种方式失败,则可以使用try-except结构以所需方式处理潜在异常。
# Let's try to open a file that does not exist
# python学习交流群:103456743
file_name = 'not_existing.txt'
try:
with open(file_name, 'r') as my_file:
print('File is successfully open')
except FileNotFoundError as e:
print('Uups, file: {} not found'.format(file_name))
print('Exception: {} was raised'.format(e))
如果你不知道代码块可能引发的异常类型,则可以使用Exception捕获所有异常。此外,你可以拥有多个except语句。
def calculate_division(var1, var2):
result = 0
try:
result = var1 / var2
except ZeroDivisionError as ex1:
print("Can't divide by zero")
except Exception as ex2:
print('Exception: {}'.format(ex2))
return result
result1 = calculate_division(3, 3)
print('result1: {}'.format(result1))
result2 = calculate_division(3, '3')
print('result2: {}'.format(result2))
result3 = calculate_division(3, 0)
print('result3: {}'.format(result3))
try-except也可以在外部范围内
创建自定义异常
在你自己的应用程序中,你可以使用自定义异常向用户发出有关在应用程序运行时发生的错误的信号。
import math
# Define your own exception
# python学习交流群:103456743
class NegativeNumbersNotSupported(Exception):
pass
# Dummy example how to use your custom exception
def secret_calculation(number1, number2):
if number1 < 0 or number2 < 0:
msg = 'Negative number in at least one of the parameters: {}, {}'.format(
number1, number2)
raise NegativeNumbersNotSupported(msg)
return math.sqrt(number1) + math.sqrt(number2)
# Uncomment to see the traceback
# result = secret_calculation(-1, 1)
好啦,赶紧自己试一下吧