How can I achieve user defined exception in Python?
本问题已经有最佳答案,请猛点这里访问。
有许多内置的异常类,如EOFError、KeyboardInterrupt等。但我如何创建自己的异常类。例如,如果我想保持约束,用户应该输入长度至少为3的字符串。
您可以在类中定义异常,也可以在下面创建自己的异常类。
/ * *定义一个扩展exception的异常类* /
类Your_Exception扩展Exception:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | // redefine exception with a message public function __construct($message, $code = 0, Exception $previous = null): //Call Parent constructor parent::__construct($message, $code, $previous); // custom string representation of object public function __to_String(): return __CLASS__ .": [{$this->code}]: {$this->message} "; public function user_defined_Function() : echo"user defined exception exception "; |
检查此代码是否有用户定义的异常:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | class ShortInputException(Exception): def __init__(self,length,atleast): Exception.__init__(self) self.length = length self.atleast = atleast try: text = input('Enter some text: ') if len(text) < 3: raise ShortInputException(len(text),3) except EOFError: print('It is end of file.') except ShortInputException as ex: print('ShortInputException: You entered {0} length long text. Expected text size is {1}'.format(ex.length,ex.atleast)) except KeyboardInterrupt: print('You interrupted the program execution.') else: print('No exception/s raised.') print('You entered: {0}'.format(text)) |