我正在尝试创建一个只处理错误的类。调用函数时,请使用class方法,这样,如果用户输入错误,错误处理类中的方法就会停止函数的执行。
using System;
using System.Collections.Generic;
public class Program
{
public static void Main()
{
foreach(var i in GetCol()) {
Console.WriteLine(i);
}
}
private static List<int> GetCol() {
Console.WriteLine("I have been called");
return new List<int>(){1, 2, 3, 4};
}
}
/* Output
I have been called
1
2
3
4 */
所以,我想要的输出是:
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
答案 0 :(得分:7)
try
块不会生成异常,因为表达式评估为true / false,而且您的奇/偶校验逻辑也是错误的。
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建议将方法更改为类方法。