有许多内置的异常类,如EOFError,KeyboardInterrupt等。但是我如何创建自己的异常类。例如,如果我想保持约束,用户应输入长度至少为3的字符串。
答案 0 :(得分:1)
检查此代码是否存在用户定义的异常:
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))
答案 1 :(得分:1)
您可以在类中定义例外,也可以在下面创建自己的例外类。
/ ** *定义一个扩展Exception的异常类 * /
class Your_Exception扩展了Exception:
// 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}\n";
public function user_defined_Function() :
echo "user defined exception exception\n";