gpt4 book ai didi

python-3.x - 如何在不将错误处理写入函数的情况下创建自定义错误处理类

转载 作者:行者123 更新时间:2023-12-04 23:36:02 25 4
gpt4 key购买 nike

我正在尝试创建一个只处理错误的类。在调用函数时使用类方法,以便错误处理类中的方法在用户输入错误时停止函数的执行。

class Error(Exception):
pass

class UserError(Error):
def handle_even(number):
try: number % 2 == 0
except: raise UserError.handle_even('error: odd number\n')
def handle_odd(number):
try: number % 2 != 0
except: raise UserError.handle_odd('error: even number\n')


def take_even(number):
print(number) #if user input is bad, this shouldn't execute

def take_odd(number):
print(number) #if user input is bad, this shouldn't execute



take_even(UserError.handle_even(5)) # I expect this to print 'error: odd number'
take_odd(UserError.handle_odd(4)) # I expect this to print 'error: even number'

所以,我想要的输出是:

error: odd number
error: even number

但是,我得到的输出是:

None
None

最佳答案

try block 不会产生异常,因为表达式评估是真/假,而且您的奇数/偶数检查逻辑是错误的。

class Error(Exception):
pass

class UserError(Error):
@classmethod
def handle_even(cls, number):
if number % 2 != 0:
raise Error('error: odd number\n')

return number

@classmethod
def handle_odd(cls, number):
if number % 2 == 0:
raise Error('error: even number\n')

return number


def take_even(number):
print(number) # if user input is bad, this won't execute

def take_odd(number):
print(number) # if user input is bad, this won't execute

# This will raise an 'Error' exception (error: odd number)
take_even(UserError.handle_even(5))

# This will raise an 'Error' exception (error: even number)
take_odd(UserError.handle_odd(4))

您可以像这样处理这些特定的Error 异常:

try:
take_even(UserError.handle_even(5))
except Error as e:
print(e) # print 'error: odd number'

try:
take_odd(UserError.handle_odd(4))
except Error as e:
print(e) # print 'error: even number'

编辑:根据@NathanVērzemnieks 的建议将方法更改为类方法。

关于python-3.x - 如何在不将错误处理写入函数的情况下创建自定义错误处理类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55506164/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com