0
有很多内置的异常类,如EOFError,KeyboardInterrupt等,但是我怎样才能创建自己的异常类。例如,如果我想保持约束,那么用户应该输入一个长度最少为3的字符串。如何在Python中实现用户定义的异常?
有很多内置的异常类,如EOFError,KeyboardInterrupt等,但是我怎样才能创建自己的异常类。例如,如果我想保持约束,那么用户应该输入一个长度最少为3的字符串。如何在Python中实现用户定义的异常?
检查此代码为用户定义的异常:
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))
您可以在类定义的异常或者,也可以在下面创建自己的异常类。
/** * 定义延伸异常 */
类Your_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";